JSON Schema简介:
json是数据交互的常用数据格式,JSON Schema是对json数据约束的一个标准。
JSON Schema官网:
JSON Schema | The home of JSON Schema
JSON Schema官网教程:
Getting Started Step-By-Step | JSON Schema
JSON Schema校验工具:
JSON Schema Validator - Newtonsoft
JSON Schema使用方式:
JsonSchemaUtil.json_schema(instance=json_data, schema=my_schema)
该函数首先验证所提供的schema本身是否有效(无效,则抛出 jsonschema.exceptions.SchemaError 异常),然后再验证json数据(校验不通过,则抛出 jsonschema.exceptions.ValidationError 异常)
JSON Schema应用:
python代码如下:
import jsonschema
def json_schema(cls, json_data):
json_schema = {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.com/product.schema.json",
"title": "iHRM断言",
"description": "响应体的数据校验",
"type": "object",
"properties":
{
"success": {
"description": '操作成功标记',
"type": "boolean",
"const": True
},
"code": {
"description": '错误码',
"type": "number",
"const": 10000
},
"message": {
"description": '消息',
"type": "string",
"pattern": "成功"
},
"data": {
"description": '响应返回的数据,失败返回空'
}
},
"required": ["success", "code", "message"]
}
# 验证:
jsonschema.validate(instance=json_data, schema=json_schema)