从Python字典生成JSON Schema的方法有多种。下面是一种常见的方法:
import json
from jsonschema import Draft7Validator, validators
def from_dict_to_schema(data):
def extend_with_default(validator_class):
validate_properties = validator_class.VALIDATORS["properties"]
def set_defaults(validator, properties, instance, schema):
for error in validate_properties(
validator, properties, instance, schema
):
yield error
for property, subschema in properties.items():
if "default" in subschema:
instance.setdefault(property, subschema["default"])
return validators.extend(
validator_class, {"properties": set_defaults}
)
MyValidator = extend_with_default(Draft7Validator)
def from_dict(validator, dct, instance, schema):
if not isinstance(instance, dict):
yield validators.ValidationError("Instance is not a dictionary")
return
for k, v in dct.items():
if isinstance(v, dict):
if "type" not in v:
v["type"] = "object"
yield from_dict(validator, v, instance.get(k, {}), schema)
else:
instance[k] = v
schema = {}
validator = MyValidator(schema)
validator.validate(data)
for error in from_dict(validator, data, {}, schema):
raise validators.ValidationError(error)
return schema
data = {
"name": "John Doe",
"age": 30,
"email": "johndoe@example.com"
}
schema = from_dict_to_schema(data)
这样,你就可以从Python字典生成对应的JSON Schema了。生成的JSON Schema可以用于验证符合该模式的JSON数据。
关于JSON Schema的概念、分类、优势、应用场景以及腾讯云相关产品和产品介绍链接地址,可以参考以下内容:
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云