Created
April 26, 2021 14:50
-
-
Save pifabs/8a19bc74e7f7223e45ac682a1f3078a3 to your computer and use it in GitHub Desktop.
JSON Schema validator
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
# example.py | |
from jsonschema import FormatChecker | |
from .jsonschema_validator import get_validator | |
USER_SCHEMA = { | |
"$schema":"http://json-schema.org/draft-07/schema#", | |
"title":"User", | |
"type" : "object", | |
"properties" : { | |
"email": { | |
"type" : "string", | |
"format": "email" | |
}, | |
"pwd": { | |
"type" : "string", | |
"minLength": 2, | |
"maxLength": 64 | |
}, | |
"age": { | |
"type" : "integer", | |
"minimum": 18, | |
"maximum": 50 | |
} | |
}, | |
"additionalProperties": False, | |
"required": ["email", "pwd", "age"] | |
} | |
# Create a validator function for a given schema | |
validate = get_validator(USER_SCHEMA) | |
# Pass data to the validator function | |
errors = validate( | |
data={"email": "test@gmail.com", "pwd": "password"}, | |
format_checker=FormatChecker() | |
) | |
if errors: | |
print(errors) | |
# [ | |
# { | |
# 'message': "'test' is not a 'email'", | |
# 'key': 'email', | |
# 'context': 'format' | |
# }, | |
# { | |
# 'message': "'age' is a required property", | |
# 'key': 'age', | |
# 'context': 'required' | |
# } | |
# ] |
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
# validator.py | |
import re | |
from jsonschema import ( | |
exceptions, | |
Draft7Validator, | |
FormatChecker | |
) | |
def get_validator(schema): | |
def validator(*args, **kwargs): | |
def _get_error(err): | |
return { | |
"message": err.message, | |
"key": get_offending_key(err), | |
"context": err.validator | |
} | |
try: | |
v = Draft7Validator( | |
schema, | |
format_checker=kwargs.get("format_checker") | |
) | |
errors = sorted(v.iter_errors(kwargs.get("data")), key=str) | |
return list( | |
map(lambda err: _get_error(err), errors) | |
) if len(errors) else None | |
except exceptions.ValidationError as v: | |
raise v | |
return validator | |
def get_offending_key(err): | |
return (re.findall(r"\'.*?\'", err.message)[0].replace("'", "") or "") \ | |
if not len(err.path) else "".join( | |
map( | |
lambda part: str("[{}]".format(part) if isinstance(part, int) else part), | |
err.path | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment