Skip to content

Instantly share code, notes, and snippets.

@nmarley
Last active May 13, 2020 21:46
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nmarley/afe61a36f71ed1e4a9728c0f5f6f7f6f to your computer and use it in GitHub Desktop.
Save nmarley/afe61a36f71ed1e4a9728c0f5f6f7f6f to your computer and use it in GitHub Desktop.
Python JSON Schema validation example

test json schema validation

Setup Virtualenv

$ virtualenv ./venv
$ ./venv/bin/pip install -r requirements.txt

Test/Play:

$ ./venv/bin/python ./v.py
appdirs==1.4.3
functools32==3.2.3.post2; python_version < '3.0'
jsonschema==2.6.0
packaging==16.8
pycodestyle==2.3.1
pyparsing==2.2.0
simplejson==3.10.0
six==1.10.0
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "InventoryItem",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"price": {
"type": "number",
"minimum": 0
},
"sku": {
"description": "Stock Keeping Unit",
"type": "integer"
}
},
"required": ["name", "price"]
}
import jsonschema
import simplejson as json
with open('schema-example.json', 'r') as f:
schema_data = f.read()
schema = json.loads(schema_data)
json_obj = {"name": "eggs", "price": 21.47}
jsonschema.validate(json_obj, schema)
json_obj = {"name": "eggs", "price": "blue"}
jsonschema.validate(json_obj, schema)
# jsonschema.exceptions.ValidationError: 'blue' is not of type 'number'
#
# Failed validating 'type' in schema['properties']['price']:
# {'type': 'number'}
#
# On instance['price']:
# 'blue'
@j0nimost
Copy link

How can we test required?

@patricionicola
Copy link

remove name....
json_obj = {"price": 21.47}
jsonschema.validate(json_obj, schema)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment