有一些库可用于在 Python 中将 JSON 转换为 JSON Schema,例如 jsonschema、json-schema-generator 和 json-schema-tools。将 JSON 对象转换为 JSON 模式的过程通常涉及创建 JSON 模式类的实例,然后递归遍历 JSON 对象以填充类的属性和属性。
对于您提供的示例,生成 JSON 架构的一种方法是首先创建一个空白架构对象,然后遍历原始 JSON 对象中的键和值,并使用这些值动态填充架构的属性和属性目的。
下面是一个示例,说明如何使用 jsonschema 库将 JSON 转换为 JSON 模式,假设 JSON 对象存储在名为 json_obj 的变量中:
从 jsonschema 导入 Draft4Validator、FormatChecker
从 jsonschema.exceptions 导入 best_match
def json_to_schema(json_obj):
# 创建一个空的模式对象
架构= {
"$schema": "http://json-schema.org/schema#",
“类型”:“对象”,
“特性”: {}
}
# Iterate over the keys and values in the JSON object
for key, value in json_obj.items():
# If the value is a nested JSON object, recursively convert it to a schema
if isinstance(value, dict):
schema["properties"][key] = json_to_schema(value)
else:
# Otherwise, add the key and value to the schema's properties
schema["properties"][key] = {"type": "string"}
return schema
json_schema = json_to_schema(json_obj)
这样,您就可以生成带有动态键的 JSON 模式,但请注意,这只是一个示例,可能需要根据您的实际用例和要求进行一些调整。