如何使用jq基于id键合并两个JSON数组生成指定结构?
使用jq合并两个JSON文件的解决方案
问题背景
我有两个JSON文件需要合并,但不确定在jq中应使用何种操作/函数,尝试的命令未得到预期结果。
文件内容
color.json
[{"id":1,"color":"red"},{"id":2,"color":"green"},{"id":3,"color":"blue"}]
shape.json
[ { "shape": "square", "color": { "id": 1, "name": "red" }, "texture": "smooth" }, { "shape": "circle", "color": { "id": 2, "name": "green" }, "texture": "smooth" }, { "shape": "triangle", "color": { "id": 3, "name": "blue" }, "texture": "smooth" }, { "shape": "triangle", "color": { "id": 3, "name": "blue" }, "texture": "rough" } ]
期望输出
[ { "id": 1, "color": "red", "shapes": [ { "shape": "square", "texture": "smooth" } ] }, { "id": 2, "color": "green", "shapes": [ { "shape": "circle", "texture": "smooth" } ] }, { "id": 3, "color": "blue", "shapes": [ { "shape": "triangle", "texture": "smooth" }, { "shape": "triangle", "texture": "rough" } ] } ]
尝试过的命令
jq 'JOIN(INDEX(inputs[];.id);.[];.color.id | tostring;add)' shape.json color.json
解决方案
使用以下jq命令可以得到预期结果:
jq -n ' $colors = input | INDEX(.id); $shapes_by_id = input | group_by(.color.id) | map({ id: .[0].color.id, shapes: map({shape, texture}) }) | INDEX(.id); $colors[] | . + $shapes_by_id[.id] ' color.json shape.json
命令说明
-n参数:阻止jq自动读取标准输入,改用input命令显式读取指定文件- 构建颜色索引:读取
color.json,用INDEX(.id)生成以id为键的对象,方便快速查找颜色信息 - 构建形状分组索引:读取
shape.json,用group_by(.color.id)按颜色ID分组,每个分组提取shape和texture字段组成shapes数组,再转成以id为键的索引对象 - 合并数据:遍历颜色索引中的每个条目,将对应的形状数组合并到颜色对象中,最终输出合并后的数组
内容的提问来源于stack exchange,提问作者agyuajcam
相关产品推荐
相关产品推荐

