python开发接口时,使用jsonschema模块对数据进行校验
import jsonschema
schema = {
"type": "object", # 先声明每个键都是对象
"properties": { # 声明每个键对应的值的类型
"version_no": {"type": "string"},
"versions": {
"type": "array", # 如果键对应的值是列表数据类型,则需要声明类型为array,然后再声明列表里面的键对应的值
"minItems": 1,
"items": {
"type": "object", # 字典对象
"required": ["name", "type"], # 必填字段
"properties": { # 声明键对应的值的类型约束等
"name": {
"type": "string",
"minLength": 1
},
"type": {
"type": "string",
"enum": ["python", "java"]
},
"size": {
"type": "number",
},
}
}
},
},
"required": ["version_no", "versions"] # 最外围的键的约束
}
data = {
"version_no": "x123",
"versions": [
{
"name": "jack",
"type": "python",
"size": 123
},
{
"name": "will",
"type": "java",
}
]
}
def schema_check(data, schema):
try:
jsonschema.validate(date, schema)
print("data中的数据通过自定义的json schema校验")
except jsonschema.exceptions.ValidationError as e;
print(e.message, "data数据没有通过schema格式校验")
if __name__ == '__main__':
schema_check(data, schema)
-------------------------------------------
个性签名:代码过万,键盘敲烂!!!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!