Search code examples
pythonjsonschema

make jsonSchema enum attribute conditionally required with useful error message


I might be doing this wrong because the error message is not helpful, even though this "works".

I have an enum (field1) that can be aaa or bbb.

If it's aaa then field2 must be required. If it's not aaa then field2 can be optional.

I have this now:

"anyOf": [
    {
        "properties": {
            "field1": {
                "const": "aaa"
            }
        },
        "required": [
            "field2"
        ]
    },
    {
        "properties": {
            "field1": {
                "const": "bbb"
            }
        }
    }
]

But this is the error I get if field1 = aaa and field2 is not specified:

E           jsonschema.exceptions.ValidationError: 'bbb' was expected
E           
E           Failed validating 'const' in schema[1]['properties']['field1']:
E               {'const': 'bbb'}
E           
E           On instance['httpMethod']:
E               'aaa'

I was expecting an error more like "field2" expected because schema[1]['properties']['field1'] == bbb

Am I using this incorrectly?


Solution

  • If you are using >= draft-07, I guess if-then(-else) will give you the best error in your case.

    from jsonschema import Draft7Validator
    
    schema = {
        "type": "object",
        "properties": {
            "field1": {
                "enum": [
                    "aaa",
                    "bbb"
                ]
            },
            "field2": {
                "type": "string"
            }
        },
        "if": {
            "properties": { "field1": { "const": "aaa" } }
        },
        "then": {
            "required": [ "field2" ]
        }
    }
    
    obj = {
        "field1": "aaa",
    }
    
    Draft7Validator(schema).validate(obj)
    

    It will generate the error:

    Traceback (most recent call last):
      File "error.py", line 28, in <module>
        Draft7Validator(schema).validate(obj)
      File "(...)/jsonschema/validators.py", line 353, in validate
        raise error
    jsonschema.exceptions.ValidationError: 'field2' is a required property
    
    Failed validating 'required' in schema['if']['then']:
        {'required': ['field2']}
    
    On instance:
        {'field1': 'aaa'}