Created
November 21, 2017 13:42
-
-
Save arthuralvim/8c313619d57ba2bf594a295c11331af9 to your computer and use it in GitHub Desktop.
Testing 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
# pip install jsonschema | |
import json | |
from jsonschema import Draft4Validator | |
lista_exemplo = [ | |
{'attr1': 'A', 'attr2': 2, 'attr3': 3, 'attr4': 4}, | |
{'attr1': 1, 'attr2': 2, 'attr3': 3, 'attr4': 4, 'attr5': 5}, | |
{'attr1': 1, 'attr2': 2, 'attr3': 3, 'attr4': 4}, | |
{'attr1': 1, 'attr2': 2, 'attr3': 3, 'attr4': 4}, | |
{'attr1': 1, 'attr2': 2, 'attr3': 3, 'attr4': 4}, | |
{'attr1': 1, 'attr2': 2, 'attr3': 3, 'attr4': 4}, | |
] | |
class InstanceValidator(object): | |
schema = { | |
"type" : "object", | |
"properties" : { | |
"attr1" : {"type" : "number"}, | |
}, | |
"required": ["attr5"] | |
} | |
def __init__(self, instance): | |
self.instance = instance | |
@classmethod | |
def schema_is_valid(cls): | |
return True if not Draft4Validator.check_schema(cls.schema) else False | |
@property | |
def is_valid(self): | |
return Draft4Validator(self.schema).is_valid(self.instance) | |
@property | |
def errors(self): | |
return sorted(Draft4Validator(self.schema).iter_errors(self.instance), key=lambda e: e.path) | |
print(InstanceValidator.schema_is_valid()) | |
print('---') | |
for ex in lista_exemplo: | |
iv = InstanceValidator(ex) | |
if iv.is_valid: | |
print(ex) | |
print('---') | |
else: | |
print(ex) | |
print(iv.errors) | |
print('-x-') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment