在比较两个 JSON 文件时,忽略特定属性可以使用以下方法:
import json
# 加载 JSON 文件1
with open('file1.json', 'r') as file:
data1 = json.load(file)
# 加载 JSON 文件2
with open('file2.json', 'r') as file:
data2 = json.load(file)
def compare_dicts(dict1, dict2, ignore_keys):
# 创建一个新的字典,存储忽略指定属性后的数据
new_dict1 = dict(dict1)
new_dict2 = dict(dict2)
# 忽略指定的属性
for key in ignore_keys:
if key in new_dict1:
del new_dict1[key]
if key in new_dict2:
del new_dict2[key]
# 比较字典对象
return new_dict1 == new_dict2
# 忽略比较 'ignore' 属性
ignore_keys = ['ignore']
result = compare_dicts(data1, data2, ignore_keys)
if result:
print("两个 JSON 文件相同")
else:
print("两个 JSON 文件不同")
这样,比较两个 JSON 文件时将会忽略指定属性,只比较其他属性的值是否相同。