如何使用Python对比两个JSON文件并将可读差异写入Output.json
Python实现两个JSON文件比对并输出可读差异方案
方案1:使用deepdiff第三方库(推荐,代码量少、差异维度清晰)
- 先安装依赖包:
pip install deepdiff - 完整实现代码:
import json from deepdiff import DeepDiff # 读取两个待比对JSON文件 with open("File1.json", "r", encoding="utf-8") as f1: json_data1 = json.load(f1) with open("File2.json", "r", encoding="utf-8") as f2: json_data2 = json.load(f2) # 生成结构化差异,配置参数保障可读性 diff_result = DeepDiff(json_data1, json_data2, ensure_ascii=False) # 格式化输出差异到目标文件 with open("Output.json", "w", encoding="utf-8") as out_f: json.dump(diff_result, out_f, indent=2, ensure_ascii=False)
- 输出差异默认包含清晰的分类字段:
dictionary_item_added:File2 比 File1 新增的键值对dictionary_item_removed:File2 比 File1 删减的键值对values_changed:同路径下的数值变动,会同时标注旧值和新值list_added/list_removed:数组类字段的元素增删内容
方案2:纯原生Python实现(无需第三方依赖)
如果运行环境不能安装额外包,可以使用递归比对的原生实现:
import json def compare_json(a, b, path=""): diff = {} # 比对字典类型 if isinstance(a, dict) and isinstance(b, dict): for key in a.keys() - b.keys(): full_path = f"{path}.{key}" if path else key diff[f"removed:{full_path}"] = a[key] for key in b.keys() - a.keys(): full_path = f"{path}.{key}" if path else key diff[f"added:{full_path}"] = b[key] for key in a.keys() & b.keys(): sub_path = f"{path}.{key}" if path else key sub_diff = compare_json(a[key], b[key], sub_path) if sub_diff: diff.update(sub_diff) # 比对数组类型 elif isinstance(a, list) and isinstance(b, list): if len(a) != len(b): diff[f"length_changed:{path}"] = f"旧长度:{len(a)},新长度:{len(b)}" for idx, (item_a, item_b) in enumerate(zip(a, b)): sub_path = f"{path}[{idx}]" sub_diff = compare_json(item_a, item_b, sub_path) if sub_diff: diff.update(sub_diff) # 比对基础类型值 else: if a != b: diff[f"value_changed:{path}"] = {"old_value": a, "new_value": b} return diff if __name__ == "__main__": with open("File1.json", "r", encoding="utf-8") as f1, open("File2.json", "r", encoding="utf-8") as f2: j1, j2 = json.load(f1), json.load(f2) res = compare_json(j1, j2) with open("Output.json", "w", encoding="utf-8") as out_f: json.dump(res, out_f, indent=2, ensure_ascii=False)
内容的提问来源于stack exchange,提问作者Noman
相关产品推荐
相关产品推荐

