要比较多个JSON对象的模式,可以使用以下方法:
import jsonschema
def compare_json_schemas(schema1, schema2):
try:
jsonschema.validate(schema1, schema2)
return True
except jsonschema.exceptions.ValidationError:
return False
# 示例
schema1 = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number"}
}
}
schema2 = {
"type": "object",
"properties": {
"name": {"type": "string"}
}
}
result = compare_json_schemas(schema1, schema2)
print(result) # 输出:False
{
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number"}
}
}
将以上模式保存为一个JSON文件,然后使用类似的方式创建其他模式文件。然后,可以使用jsonschema库来比较两个模式文件。
import jsonschema
def compare_json_schema_files(file1, file2):
with open(file1, "r") as f1, open(file2, "r") as f2:
schema1 = json.load(f1)
schema2 = json.load(f2)
try:
jsonschema.validate(schema1, schema2)
return True
except jsonschema.exceptions.ValidationError:
return False
# 示例
result = compare_json_schema_files("schema1.json", "schema2.json")
print(result) # 输出:False
以上是两种常见的比较多个JSON对象模式的解决方法,可以根据实际需求选择适合的方法。
上一篇:比较多个ID并从表中提取数据