jsonschema


jsonschema is an implementation of JSON Schema for Python (supporting 2.7+ including Python 3).

Usage


In [ ]:
from jsonschema import validate

In [ ]:
# A sample schema, like what we'd get from json.load()
schema = {
    "type" : "object",
    "properties" : {
        "price" : {"type" : "number"},
        "name" : {"type" : "string"},
    },
}

In [ ]:
# If no exception is raised by validate(), the instance is valid.
validate(instance={"name" : "Eggs", "price" : 34.99}, schema=schema)

In [ ]:
validate(
    instance={"name" : "Eggs", "price" : "Invalid"},
    schema=schema,
)


---------------------------------------------------------------------------
ValidationError                           Traceback (most recent call last)
<ipython-input-5-e1e543273d1f> in <module>
      1 validate(
      2     instance={"name" : "Eggs", "price" : "Invalid"},
----> 3     schema=schema,
      4 )

~/Development/jsonschema/jsonschema/validators.py in validate(instance, schema, cls, *args, **kwargs)
    899     error = exceptions.best_match(validator.iter_errors(instance))
    900     if error is not None:
--> 901         raise error
    902 
    903 

ValidationError: 'Invalid' is not of type 'number'

Failed validating 'type' in schema['properties']['price']:
    {'type': 'number'}

On instance['price']:
    'Invalid'

It can also be used from console:


In [ ]:
!echo '{"name" : "Eggs", "price" : 34.99}' > /tmp/sample.json

In [ ]:
!echo '{"type" : "object", "properties" : {"price" : {"type" : "number"}, "name" : {"type" : "string"}}}' > /tmp/sample.schema

In [ ]:
!jsonschema -i /tmp/sample.json /tmp/sample.schema

Do your own experiments here...

Try jsonschema youself by adding your code below and running your own experiments 👇


In [ ]:
import jsonschema

# your code here
jsonschema.