You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术求助:如何比较两个技术层面一致的JSON文件并输出差异,含2个CSV、1个Excel

比较同结构JSON文件并输出差异的实用方法

方法一:Python脚本实现(灵活定制)

如果需要自定义差异输出格式,Python是最佳选择。推荐使用deepdiff库,专门处理嵌套结构的差异对比:

  • 步骤1:安装依赖
pip install deepdiff
  • 步骤2:编写对比脚本
import json
from deepdiff import DeepDiff

def compare_json(file1_path, file2_path):
    # 读取两个JSON文件
    with open(file1_path, 'r', encoding='utf-8') as f1:
        json1 = json.load(f1)
    with open(file2_path, 'r', encoding='utf-8') as f2:
        json2 = json.load(f2)
    
    # 执行对比,忽略数组顺序差异
    diff = DeepDiff(json1, json2, ignore_order=True)
    
    # 格式化输出差异
    if not diff:
        print("两个JSON文件完全一致")
    else:
        print("JSON文件差异如下:")
        if 'values_changed' in diff:
            print("\n值变更项:")
            for path, change in diff['values_changed'].items():
                print(f"路径: {path}")
                print(f"旧值: {change['old_value']}")
                print(f"新值: {change['new_value']}\n")
        if 'dictionary_item_added' in diff:
            print("\n新增项:")
            for path in diff['dictionary_item_added']:
                target_key = path.strip('root.')
                print(f"路径: {path},值: {json2[target_key]}\n")
        if 'dictionary_item_removed' in diff:
            print("\n删除项:")
            for path in diff['dictionary_item_removed']:
                target_key = path.strip('root.')
                print(f"路径: {path},值: {json1[target_key]}\n")

# 调用示例,替换为你的文件路径
compare_json('file1.json', 'file2.json')

这个脚本会清晰展示值变更、新增、删除的内容,适合需要详细分析差异的场景。

方法二:命令行工具快速对比

如果只是需要快速验证差异,无需定制,可以用jq配合diff命令:

  • 步骤1:安装jq(根据系统选择命令)

    • Ubuntu/Debian: sudo apt install jq
    • macOS: brew install jq
    • Windows:下载二进制文件并添加到系统环境变量
  • 步骤2:执行对比命令

diff <(jq '.' file1.json) <(jq '.' file2.json)

该命令先通过jq格式化JSON输出,再用diff对比文本差异,适合快速验证一致性或查看文本层面的差异。

注意事项

  • 确保两个JSON文件结构完全一致,否则差异结果会包含结构差异项(如字段类型变化),可调整DeepDiff参数忽略此类差异。
  • 处理大文件时,Python脚本的内存占用更低,命令行diff可能出现卡顿。
  • 若JSON数组顺序不影响业务逻辑,DeepDiff的ignore_order=True参数可避免因顺序不同误判差异。

内容的提问来源于stack exchange,提问作者Alexander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 10:30:43