python-fastjsonschema icon indicating copy to clipboard operation
python-fastjsonschema copied to clipboard

Insert defaults before validation

Open timgkeller opened this issue 5 years ago • 0 comments

At the moment this code fails:

import fastjsonschema

schema = {
    "type": "object",
    "properties": {
        "class_name": {
            "const": "some_class"
        },
        "some_property": {
            "type": "number",
            "default": 1
        }
    },
    "required": ["class_name", "some_property"],
    "additionalProperties": False
}
obj = {"class_name": "some_class"}
fastjsonschema.exceptions.JsonSchemaException: data must contain ['class_name', 'some_property'] properties

However, if I remove "some_property" from the list of required properties, the resulting object would be valid during a second validation against the original schema:

import fastjsonschema

schema = {
    "type": "object",
    "properties": {
        "class_name": {
            "const": "some_class"
        },
        "some_property": {
            "type": "number",
            "default": 1
        }
    },
    "required": ["class_name"],
    "additionalProperties": False
}
obj = {"class_name": "some_class"}

fastjsonschema.validate(schema, obj)
print(obj)
{'class_name': 'some_class', 'some_property': 1}

This can be resolved by applying the defaults before the validation. However, if you'd like to implement this fix, be careful when handling keywords like anyOf. The insertion of the defaults would have to be undone if it turns out that a certain subschema does not match.

timgkeller avatar Oct 28 '20 09:10 timgkeller