Last active
December 17, 2015 05:19
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You usually wouldn't use
is_valid
(orassert
), so it's actually even slightly easier :).which raises a
ValidationError
when it fails.