要比较 JSON 路径是否相等,除了索引以外,可以使用以下方法:
下面是一个使用 Python 语言实现的示例代码:
def compare_json_paths(json1, json2, path=''):
if isinstance(json1, dict) and isinstance(json2, dict):
if sorted(json1.keys()) != sorted(json2.keys()):
return False
for key in json1.keys():
if not compare_json_paths(json1[key], json2[key], f"{path}.{key}"):
return False
return True
elif isinstance(json1, list) and isinstance(json2, list):
if len(json1) != len(json2):
return False
for i in range(len(json1)):
if not compare_json_paths(json1[i], json2[i], f"{path}[{i}]"):
return False
return True
else:
return json1 == json2
# 示例用法
json1 = {
'name': 'Alice',
'age': 25,
'address': {
'city': 'New York',
'zip': 12345
},
'friends': [
{'name': 'Bob', 'age': 30},
{'name': 'Charlie', 'age': 28}
]
}
json2 = {
'name': 'Alice',
'age': 25,
'address': {
'city': 'Los Angeles',
'zip': 54321
},
'friends': [
{'name': 'Bob', 'age': 30},
{'name': 'Charlie', 'age': 28}
]
}
print(compare_json_paths(json1, json2))
输出结果为 False
,因为 json1
和 json2
的 address.city
和 address.zip
的值不相等。