Search code examples
pythonjsonschemajson-schema-validatorpython-jsonschema

Json Schema validation: should raise Exception when there are unrecognized fields


A simple example:

import json
from jsonschema import validate

schema = {
    "type" : "object",
    "properties" : {
        "description" : {"type" : "string"},
        "value_c" : { "type": "object", 
                      "properties": {"x": { "type": "string" }, 
                                     "z": { "type": "string" }}, 
                      "required": ["x"], 
                      "maxProperties": 2}
    },
    "required": ["description", "value_c"]
}

my_json = json.loads('{"description": "Hello world!", "value_c": {"x": "5", "z222": "6" } }')

validate(instance=my_json, schema=schema)

There is no Exception raised after executing this code snippet. But I would like to raise an Exception when there are new unrecognized fields: in this case: z222.

Not sure if the Python library jsonschema (link) supports this feature? If no, please feel free to suggest alternatives. If yes, I think we need to change the schema definition somehow...

Environment

  • Python 3.10.6 (64 bit)

Solution

  • Credits to @Uli Sotschok

    Using Additional Properties solves my issue: raise Exception when there are new unrecognized fields.

    Full example:

    import json
    from jsonschema import validate
    
    schema = {
        "type" : "object",
        "properties" : {
            "description" : {"type" : "string"},
            "value_c" : { "type": "object", 
                          "properties": {"x": { "type": "string" }, 
                                         "z": { "type": "string" }}, 
                          "required": ["x"], 
                          "additionalProperties": False}
        },
        "required": ["description", "value_c"]
    }
    
    my_json = json.loads('{"description": "Hello world!", "value_c": {"x": "5", "z222": "6" } }')
    
    validate(instance=my_json, schema=schema)
    

    The Exception:

    ValidationError: Additional properties are not allowed ('z222' was unexpected)
    
    Failed validating 'additionalProperties' in schema['properties']['value_c']:
        {'additionalProperties': False,
         'properties': {'x': {'type': 'string'}, 'z': {'type': 'string'}},
         'required': ['x'],
         'type': 'object'}
    
    On instance['value_c']:
        {'x': '5', 'z222': '6'}