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

使用jq或jtc实现按任意键合并多个JSON文件的数组

jq 实现方案

直接执行以下命令即可完成符合要求的合并,无需提前预知键名:

jq -s 'reduce .[] as $item ({}; reduce ($item | to_entries)[] as $entry (.; .[$entry.key] += $entry.value))' 你的所有输入json文件路径

命令逻辑说明

  • -s 参数:将所有输入的JSON文件内容读入为一个数组,数组的每个元素对应单个文件的解析结果
  • 外层reduce:遍历每个输入文件的内容,初始结果为一个空对象
  • 内层reduce:将当前遍历的文件拆为键值对条目,逐个将条目的值(数组)追加到结果对象对应键的数组中

如果你的场景中可能存在值不是数组的情况,可以用下面的兼容版本,会自动把非数组值转为数组再合并:

jq -s 'reduce .[] as $item ({}; reduce ($item | to_entries)[] as $entry (.; .[$entry.key] = (.[$entry.key] // []) + (if $entry.value | type == "array" then $entry.value else [$entry.value] end)))' 你的所有输入json文件路径
jtc 实现方案

使用jtc工具可以用更简洁的命令实现:

jtc --merge=array -r *.json

执行后会直接输出合并后的结果,相同键的数组会自动追加合并。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 04:45:05