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

如何使用jq将file2内容合并至file1的evidences字段?

使用jq合并两个JSON文件的数组内容

需求说明

现有两个JSON文件:

  • file1(包含evidences数组的JSON对象):
{
    "version": "2",
    "run_id": "1",
    "crn": "crn",
    "date": "2022-11-02T02:09:30.629Z",
    "evidences": [
        {
            "version": "2",
            "id": "2d"
        },
        {
            "version": "2",
            "id": "3e"
        }
    ]
}
  • file2(纯JSON数组):
[
    {
        "version": "3",
        "id": "3d"
    },
    {
        "version": "2",
        "id": "3f"
    }
]

需要将file2中的所有元素追加到file1的evidences数组末尾,得到目标JSON:

{
    "version": "2",
    "run_id": "1",
    "crn": "crn",
    "date": "2022-11-02T02:09:30.629Z",
    "evidences": [
        {
            "version": "2",
            "id": "2d"
        },
        {
            "version": "2",
            "id": "3e"
        },
        {
            "version": "3",
            "id": "3d"
        },
        {
            "version": "2",
            "id": "3f"
        }
    ]
}

解决方案

直接使用jq的数组追加操作即可实现,执行以下命令:

jq '.evidences += input' file1 file2

命令说明

  • .evidences += input:jq会先读取file1作为初始JSON对象,再读取file2的内容作为input值,将其直接追加到.evidences数组末尾。
  • 如果需要将结果直接覆盖原file1文件(建议先备份原文件),可以用重定向:
jq '.evidences += input' file1 file2 > temp.json && mv temp.json file1

备选写法(通过变量加载文件)

也可以用--argfile参数将file2内容加载到变量中再合并:

jq --argfile extra file2 '.evidences += $extra' file1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:45:56