JoyfulPanda
JoyfulPanda

Reputation: 1037

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

Upvotes: 1

Views: 1511

Answers (2)

JoyfulPanda
JoyfulPanda

Reputation: 1037

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'}

Upvotes: 2

Şahin Murat Oğur
Şahin Murat Oğur

Reputation: 128

Maybe you can try pydantic

from pydantic import *

class Test(BaseModel):
    description: str = None
    value_c: str = None
    
    
    class Config:
       allow_population_by_field_name = True
       extra = Extra.forbid


    data = {
    "description": "This is. test descriptiion",
    "value_c": "This is test value c",
    "value_d": " Test extra field"
}

test_instance = Test(**data)

If you run the code, you will get a validation error, if you want to allow an extra field then in the config class set the extra variable as followings. By default, the extra field will be ignored.

extra= Extra.allow

Upvotes: 1

Related Questions