jsonschema - 校验Json内容和格式
1、创建对象
from pydantic import BaseModel
from typing import Listclass Person(BaseModel):name: strage: intclass Student(Person): level: int = 16friends: List[Person]
2、生成 schema
schema = Student.model_json_schema()
内容如下
{'$defs': {'Person': {'properties': {'name': {'title': 'Name', 'type': 'string'}, 'age': {'title': 'Age', 'type': 'integer'}}, 'required': ['name', 'age'], 'title': 'Person', 'type': 'object'}}, 'properties': {'name': {'title': 'Name', 'type': 'string'}, 'age': {'title': 'Age', 'type': 'integer'}, 'level': {'title': 'Level', 'type': 'integer'}, 'friends': {'items': {'$ref': '#/$defs/Person'}, 'title': 'Friends', 'type': 'array'}}, 'required': ['name', 'age', 'level', 'friends'], 'title': 'Student', 'type': 'object'}
3、生成测试数据
对象转 json 字符串
fre0 = Person(age=15, name='alice')
fre1 = Person(age=17, name='Allen') stu = Student(age=15, name='Betty', level = 3, friends = [fre0, fre1]) d1 = stu.__dict__
print(d1) # {'name': 'Betty', 'age': 15, 'level': 3, 'friends': {name='alice', age=15}, Person(name='Allen', age=17)]}import json
json.dumps(d1, default=lambda obj:obj.__dict__, sort_keys=True, indent=4 ) # Object of type Person is not JSON serializable
json_str = '''
{"age": 15, "friends": [{"age": 15, "name": "alice"}, {"age": 17, "name": "Allen"}], "level": 3, "name": "Betty"}
'''
4、校验 validate
d2 = json.loads(json_str)schema = {'$defs': {'Person': {'properties': {'name': {'title': 'Name', 'type': 'string'}, 'age': {'title': 'Age', 'type': 'integer'}}, 'required': ['name', 'age'], 'title': 'Person', 'type': 'object'}}, 'properties': {'name': {'title': 'Name', 'type': 'string'}, 'age': {'title': 'Age', 'type': 'integer'}, 'level': {'title': 'Level', 'type': 'integer'}, 'friends': {'items': {'$ref': '#/$defs/Person'}, 'title': 'Friends', 'type': 'array'}}, 'required': ['name', 'age', 'level', 'friends'], 'title': 'Student', 'type': 'object'}from jsonschema import validatetry:ret = validate(instance=d2, schema=schema)print(ret) # 返回 None 代表没问题 if ret == None:print('-- json 格式符合')else:print('xx json 格式不符合')
except Exception as err:print('xx json 验证失败 ')
5、错误情况
以上json 没问题,如果把 json 数据 或字典 故意处理为错误的数据类型,或格式,如下:
{"age": 15, "friends": [{"age": 15, "name": "alice"}, {"age": 17, "name": "Allen"}], "level": 3, "name": 12}
validate 会报出 Error
Traceback (most recent call last):File "<stdin>", line 1, in <module>File "/Users/xxx/python3.11/site-packages/jsonschema/validators.py", line 1332, in validateraise error
jsonschema.exceptions.ValidationError: 12 is not of type 'string'Failed validating 'type' in schema['properties']['name']:{'title': 'Name', 'type': 'string'}On instance['name']:12
2024-09-20(六)