比较两个JSON文件并打印差异报表可以通过以下步骤实现:
open()
函数,将两个JSON文件分别读取为字符串或字典对象。下面是一个示例的Python代码,用于比较两个JSON文件并打印差异报表:
import json
def compare_json(file1, file2):
# 读取两个JSON文件
with open(file1, 'r') as f1, open(file2, 'r') as f2:
json1 = json.load(f1)
json2 = json.load(f2)
# 比较两个JSON数据
diff = {}
for key in json1:
if key not in json2:
diff[key] = {'status': 'deleted', 'value': json1[key]}
elif json1[key] != json2[key]:
diff[key] = {'status': 'modified', 'old_value': json1[key], 'new_value': json2[key]}
for key in json2:
if key not in json1:
diff[key] = {'status': 'added', 'value': json2[key]}
# 打印差异报表
for key, value in diff.items():
if value['status'] == 'deleted':
print(f"Key '{key}' is deleted. Value: {value['value']}")
elif value['status'] == 'modified':
print(f"Key '{key}' is modified. Old value: {value['old_value']}, New value: {value['new_value']}")
elif value['status'] == 'added':
print(f"Key '{key}' is added. Value: {value['value']}")
# 示例用法
compare_json('file1.json', 'file2.json')
请注意,以上代码仅为示例,实际应用中可能需要根据具体需求进行适当的修改和优化。
领取专属 10元无门槛券
手把手带您无忧上云