如何使用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
相关产品推荐
相关产品推荐

