https://ceshiren.com/t/topic/16658.json
// # 预期的 JSON 文档结构
{
"name": "Hogwarts",
"Courses": ["Mock", "Docker"]
}
// jsonschema
{
"$schema": "http://json-schema.org/draft-06/schema#",
"$ref": "#/definitions/Welcome",
"definitions": {
"Welcome": {
"type": "object",
"additionalProperties": false,
"properties": {
"name": {
"type": "string"
},
"Courses": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": ["Courses", "name"],
"title": "Welcome"
}
}
}
- 复制 JSON 数据
- 粘贴到在线生成工具中
- 自动生成 JSON Schema 数据
JSON Schema 在线生成工具:https://app.quicktype.io
- 安装:
pip install genson。
- 调用方法生成对应的 JSONSchema 数据结构。
from genson import SchemaBuilder
def generate_jsonschema(obj):
# 实例化jsonschem
builder = SchemaBuilder()
# 传入被转换的对象
builder.add_object(obj)
# 转换成 schema 数据
return builder.to_schema()
- 安装:
pip install jsonschema。
- 调用
validate() 进行验证。
def schema_validate(obj, schema):
'''
对比 python 对象与生成的 JSONSchame 的结构是否一致
'''
try:
validate(instance=obj, schema=schema)
return True
except Exception as e:
return False
- 生成JSONSchema
- 验证JSONSchema
class JSONSchemaUtils:
@classmethod
def generate_schema(cls, obj):
# 实例化jsonschem
builder = SchemaBuilder()
# 传入被转换的对象
builder.add_object(obj)
# 转换成 schema 数据
return builder.to_schema()
@classmethod
def schema_validate(cls, obj, schema):
'''
对比 python 对象与生成的 json schame 的结构是否一致
'''
try:
validate(instance=obj, schema=schema)
return True
except Exception as e:
return False