-
Notifications
You must be signed in to change notification settings - Fork 0
/
JSONSchema.py
71 lines (63 loc) · 1.53 KB
/
JSONSchema.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from json import load, loads, JSONDecodeError
from jsonschema import validate, Draft4Validator
from jsonschema.exceptions import ValidationError
person_schema = {
"type": "object",
"properties" : {
"firstname": {
"type": "string",
"minLength": 1
},
"middleInitial": {
"type": "string",
"minLength": 1,
"maxLength": 1
},
"lastName": {
"type": "string",
"minLength": 1
},
"age": {
"type": "integer",
"minimun": 0
},
"eyeColor": {
"type": "string",
"enum": ["amber", "blue", "brown", "gray", "green", "hazel", "red", "violet"]
}
},
"required": ["firstName", "lastName"]
}
p1 = '''
{
"firstName": "John",
"middleInitial": "M",
"lastName": "Cleese",
"age": 33
}'''
p2 = '''
{
"firstName": "John",
"middleInitial": 100,
"lastName": "Cleese",
"age": "Unknown"
}'''
p3 = '''
{
"firstName": "John",
"age": -10.4
}'''
validator = Draft4Validator(person_schema)
person1 = p1
person2 = p2
try:
validate(loads(person1), person_schema)
except JSONDecodeError as ex:
print(f'Invalid JSON: {ex}')
except ValidationError as ex:
print(f'Validation error: {ex}')
else:
print('JSON is Valid and confirms to schema')
for error in validator.iter_errors(loads(person2)):
print('\n-------\nError Using Draft4Validator in Person2....')
print(error, end= '\n--------\n')