jsonschema#
The jsonschema package implements the JSON schema in the python. The basic essences:
jsonschema.validationfunction validates theinstanceagainsschema. Raises thejsonschema.exceptions.ValidationErrorif validation failed.Validators are classes that specify the validation principles. Different drafts are implemented through different validators.
import jsonschema
from jsonschema import validate
validate#
The jsonschema validate function takes:
instance: object to be validated.schema: schema to validate against.cls: the validator class.
Consider the const keyword, which was only implemented only in Draft6 of the JSON schema.
import jsonschema
The schema requires instante to be exactly 11, but 10 is passed.
validate(
instance=10,
schema={"const": 11},
cls=jsonschema.Draft4Validator
)
However, since the Draft4 does not implement the const keyword, the validation passes without any errors.
The following exmaple tries exactly the same instance and schema but uses the validator that implementes the Draft6.
try:
validate(
instance=10,
schema={"const": 11},
cls=jsonschema.Draft6Validator
)
except Exception as e:
print(type(e))
print(e)
<class 'jsonschema.exceptions.ValidationError'>
11 was expected
Failed validating 'const' in schema:
{'const': 11}
On instance:
10