python-fastjsonschema
python-fastjsonschema copied to clipboard
Insert defaults before validation
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.