Skip to content
Advertisement

Representing boolean with enum options in json to generate json schema with genson

I am trying to use genson python library to build a json schema which then will be used on frontend to generate a dynamic form. In this case I want frontend to create a radio button based on schema values. But I have issue with boolean types. For example, this is how my json data looks like

configuration = {
            "displayType":  {"Opaque":True, "Border":False}
        } #Out of the two options here, only one of them can be true.

and this is how i create schema from it.

 builder = SchemaBuilder(schema_uri="https://json-schema.org/draft/2020-12/schema")
 builder.add_object(configuration)
 schema = builder.to_schema()

The generated schema looks like below,

{
    'type': 'object',
    'properties': {
        'Opaque': {
            'type': 'boolean'
        },
        'Border': {
            'type': 'boolean'
        }
    },
    'required': ['Border', 'Opaque']
}

As seen above in the required field I need to have info regarding the mutual relationship within one another but I just have a required field. Can anyone help me to modify the json data accordingly?

Advertisement

Answer

You can add this to your schema:

'not': {
    'properties': {
        'Opaque': { 'const': true },
        'Border': { 'const': true }
    }
}

In pseudocode, that is: “if Opaque is true and Border is true, then validation is false.”

Alternatively, because you require both Opaque and Border to be set, and they can only be true or false, you could use if/then/else, as in: “if Opaque is true, then Border is false, else Border is true”:

'if': {
    'properties': {
        'Opaque': { const: true }
    }
},
'then': {
    'properties': {
        'Border': { const: false }
    }
},
'else': {
    'properties': {
        'Border': { const: true }
    }
}

You can read more about adding conditions to your schema here: https://json-schema.org/understanding-json-schema/reference/conditionals.html

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement