Skip to content

Instantly share code, notes, and snippets.

@echohack
Last active December 17, 2015 05:19
Show Gist options
  • Save echohack/5557235 to your computer and use it in GitHub Desktop.
Save echohack/5557235 to your computer and use it in GitHub Desktop.
A snippet that shows how to validate json against a schema using jsonschema.
import json
import jsonschema
import requests
def get_valid_json(self, data, json_schema_url):
"""
Validates a json artifact against a published schema.
"""
s = requests.get(url=json_schema_url)
schema = s.json()
jsonschema.Draft4Validator.check_schema(schema)
jsonvalidator = jsonschema.Draft4Validator(schema)
try:
assert jsonvalidator.is_valid(data)
return data
except AssertionError as e:
raise AssertionError
@Julian
Copy link

Julian commented May 14, 2013

You usually wouldn't use is_valid (or assert), so it's actually even slightly easier :).

def get_valid_json(self, data, json_schema_url):
    schema = requests.get(url=json_schema_url).json()
    jsonschema.validate(data, schema)
    return data

which raises a ValidationError when it fails.

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