如何用jq命令合并JSON文件数组?支持按数组名控制合并
解决方案
1. 基础合并需求(合并vegetables到fruits)
要实现将vegetables数组元素合并到fruits数组,并仅输出包含合并后fruits的结果,使用以下jq命令:
jq '.fruits += .vegetables | {fruits}' input.json
命令解释:
.fruits += .vegetables:将vegetables数组的所有元素追加到fruits数组末尾,完成合并| {fruits}:过滤输出,仅保留包含合并后fruits数组的对象
执行后输出结果:
{"fruits":[{"name":"banana"},{"name":"apple"},{"name":"tomato"},{"name":"onion"}]}
2. 按数组名控制合并操作
可以通过jq的参数传递功能,动态指定目标数组和源数组,实现灵活的合并控制。
例如,通过--arg参数传入目标数组名和源数组名:
jq --arg target "fruits" --arg source "vegetables" '.[$target] += .[$source] | {($target)}' input.json
关键细节:
.[$target]和.[$source]:通过变量引用指定的数组字段{($target)}:使用计算属性名,确保输出的对象键为指定的目标数组名
如果需要切换合并方向(比如把fruits合并到vegetables),只需修改参数值即可:
jq --arg target "vegetables" --arg source "fruits" '.[$target] += .[$source] | {($target)}' input.json
3. 多数组场景下的处理
如果需要将多个数组合并到同一个目标数组,有两种常见处理方式:
方式1:直接拼接多个源数组
若明确知道要合并的数组名,可直接用+拼接后追加到目标数组:
假设JSON新增grains数组:
{ "fruits": [{"name": "banana"}, {"name": "apple"}], "vegetables": [{"name": "tomato"}, {"name": "onion"}], "grains": [{"name": "rice"}, {"name": "wheat"}] }
合并vegetables和grains到fruits的命令:
jq '.fruits += .vegetables + .grains | {fruits}' input.json
方式2:动态指定多个源数组
若源数组数量不确定或需批量指定,可使用--argjson传入源数组名列表,结合map和add批量合并:
jq --argjson sources '["vegetables", "grains"]' '.fruits += ($sources | map(.[.]) | add) | {fruits}' input.json
命令解释:
$sources | map(.[.]):遍历源数组名列表,取出对应的数组内容add:将所有取出的数组合并为一个数组.fruits += ...:将合并后的数组追加到目标数组
内容的提问来源于stack exchange,提问作者DavSev
相关产品推荐
相关产品推荐

