jsonschema

jsonschema#

The jsonschema package implements the JSON schema in the python. The basic essences:

  • jsonschema.validation function validates the instance agains schema. Raises the jsonschema.exceptions.ValidationError if 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.

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

Schema validation#

The jsonschema.validate function validates that the schema is JSON-compatible, but not the pure validators.

Note: However, it’s better to keep your schema JSON-compatible anyway.


For example, consider an attempt to pass a schema that containing a set in it’s definition, which makes it JSON-uncompatible.

schema = {
    "type": "array",
    "items": {"enum": {1, 2, 3}}
}

The attempt to use this schema results in a corresponding error.

try:
    jsonschema.validate(instance=[2], schema=schema)
except Exception as e:
    print(e)
{1, 2, 3} is not of type 'array'

Failed validating 'type' in metaschema['allOf'][1]['properties']['items']['$dynamicRef']['allOf'][3]['properties']['enum']:
    {'type': 'array', 'items': True}

On schema['items']['enum']:
    {1, 2, 3}

However, if you use the validator directly, everything will work fine fine.

schema = {
    "type": "array",
    "items": {"enum": {1, 2, 3}}
}
validator = jsonschema.Draft202012Validator(schema=schema)
validator.validate([1])