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

如何使用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

命令说明

  1. -n 参数:阻止jq自动读取标准输入,改用input命令显式读取指定文件
  2. 构建颜色索引:读取color.json,用INDEX(.id)生成以id为键的对象,方便快速查找颜色信息
  3. 构建形状分组索引:读取shape.json,用group_by(.color.id)按颜色ID分组,每个分组提取shape和texture字段组成shapes数组,再转成以id为键的索引对象
  4. 合并数据:遍历颜色索引中的每个条目,将对应的形状数组合并到颜色对象中,最终输出合并后的数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 13:52:47