使用jq合并关联JSON文件失败,请求正确实现方案
解决JSON合并的jq命令错误问题
问题根源
你的jq命令存在两个核心错误:
- 键名大小写不匹配:JSON里的用户ID键是小写的
id,但你命令里写的是大写.ID,jq对键名大小写敏感,导致找不到对应的数据。 - 未处理数组结构:File1是数组格式,原命令直接操作
.owner,没有遍历数组里的每个对象,自然无法正确修改内容。
修正后的命令
方案一(兼容旧版jq)
jq --argfile new file2.json ' ($new | INDEX(.id)) as $dict | .[] # 遍历File1数组中的每个对象 | .owner |= (if $dict[.id] then . + $dict[.id] else . end) ' file1.json
方案二(新版jq推荐写法)
--argfile在新版jq中已被标记为废弃,推荐使用--slurpfile:
jq --slurpfile new file2.json ' ($new[0] | INDEX(.id)) as $dict | .[] | .owner |= (if $dict[.id] then . + $dict[.id] else . end) ' file1.json
方案三(更简洁的写法)
如果能确定两个文件里的id是一一对应的,可以简化成:
jq --slurpfile owners file2.json ' .[] | .owner += ($owners[0] | map({(.id): .}) | add)[.owner.id] ' file1.json
执行效果
运行上述任一命令后,输出会完全符合你想要的结构:
[ { "id": 1, "name": "serviceName", "owner": { "id": 1, "name": "Nicole", "email": "nicole@email.com" } } ]
内容的提问来源于stack exchange,提问作者Nadir Y
相关产品推荐
相关产品推荐

