如何用Python对比两个JSON文件并增量更新差异内容?
仅更新JSON文件差异部分的Python实现
要实现仅更新file_two中与file_one存在差异的部分,你可以基于jsondiff获取的差异结果,直接修改file_two对应的字典对象,最后将修改后的字典写回文件即可。无需全量重写,只更新有变化的节点。
核心思路
- 读取两个JSON文件为Python字典
- 计算将
file_two转换为file_one所需的差异(注意jsondiff.diff的参数顺序:diff(目标状态, 源状态)会得到从目标到源的变更补丁,这里我们需要把file_two改成file_one,所以用diff(file_two, file_one)) - 遍历差异中的更新、插入、删除操作,对应修改
file_two的字典 - 将修改后的字典写回
file_two文件
修改后的完整代码
import json import sys import jsondiff as jd from jsondiff import diff def apply_diff(target_dict, differences): """将jsondiff的差异应用到目标字典""" # 处理更新操作 if jd.update in differences: updates = differences[jd.update] def apply_updates(obj, updates): for key, value in updates.items(): if isinstance(value, dict) and key in obj and isinstance(obj[key], dict): apply_updates(obj[key], value) else: obj[key] = value apply_updates(target_dict, updates) # 处理插入操作(如果有新增键值对) if jd.insert in differences: inserts = differences[jd.insert] def apply_inserts(obj, inserts): for key, value in inserts.items(): obj[key] = value apply_inserts(target_dict, inserts) # 处理删除操作(如果有需要移除的键值对) if jd.delete in differences: deletes = differences[jd.delete] def apply_deletes(obj, deletes): for key in deletes: if key in obj: del obj[key] apply_deletes(target_dict, deletes) def compare_and_update_json(file_one_path, file_two_path): with open(file_one_path, "r") as f1, open(file_two_path, "r") as f2: file_one = json.load(f1) file_two = json.load(f2) # 计算将file_two转换为file_one需要的差异 differences = diff(file_two, file_one, syntax='explicit') if not differences: print("两个JSON文件完全一致,无需更新") return print("检测到差异:", differences) # 应用差异到file_two字典 apply_diff(file_two, differences) # 将更新后的字典写回file_two文件 with open(file_two_path, "w") as f2: json.dump(file_two, f2, indent=2) print("已完成file_two的差异更新") if __name__ == "__main__": if len(sys.argv) != 3: print("用法:python script.py <file_one路径> <file_two路径>") sys.exit(1) compare_and_update_json(sys.argv[1], sys.argv[2])
代码说明
apply_diff函数递归处理差异中的更新、插入、删除操作,确保嵌套的字典节点也能正确更新- 调整了
diff的参数顺序,确保获取的是将file_two同步到file_one的正确补丁 - 加入了参数校验,避免用户传入错误数量的参数
- 写回文件时使用
indent=2保持JSON格式的可读性
测试示例
用你提供的示例文件测试:
file_one的secure.id为123,file_two的secure.id为456- 运行脚本后,
file_two的secure.id会被更新为123,其他内容保持不变
内容的提问来源于stack exchange,提问作者Stacker
相关产品推荐
相关产品推荐

