以下示例代码使用Python语言实现比较两个嵌套的JSON结构的方法。
import json
def compare(obj1, obj2):
if type(obj1) != type(obj2):
return False
if isinstance(obj1, dict):
for key in obj1:
if key not in obj2:
return False
if not compare(obj1[key], obj2[key]):
return False
return True
elif isinstance(obj1, list):
if len(obj1) != len(obj2):
return False
for i in range(len(obj1)):
if not compare(obj1[i], obj2[i]):
return False
return True
else:
return obj1 == obj2
# 测试
json_str1 = '{"name": "Alice", "age": 18, "address": {"city": "Beijing", "postcode": "100000"}, "friends": ["Bob", "Charlie"]}'
json_str2 = '{"name": "Bob", "age": 20, "address": {"city": "Shanghai", "postcode": "200000"}, "friends": ["Alice", "Charlie", "David"]}'
obj1 = json.loads(json_str1)
obj2 = json.loads(json_str2)
print(compare(obj1, obj2)) # False
# 修改 obj2 中的值
obj2["name"] = "Alice"
obj2["age"] = 18
obj2["address"]["city"] = "Beijing"
obj2["address"]["postcode"] = "100000"
obj2["friends"].append("Bob")
print(compare(obj1, obj2)) # True
说明:
compare
函数递归比较两个JSON对象,包括字典、列表和基本类型。False
。True
。json.loads
函数将其转换为对象。obj2
中的值,使得它和 `