使用jq基于密钥id将json数组插入到另一个

kgsdhlau  于 2023-08-08  发布在  其他
关注(0)|答案(2)|浏览(83)

抱歉问了个菜鸟问题。我需要合并两个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。但这并不是我的目标。

rkkpypqq

rkkpypqq1#

下面是一个基于reduce的方法,它简单地迭代shape.json项,将它们从colors.json添加到INDEX ed对象。最后一个map(.)将对象重新转换为数组:

jq '
  reduce input[] as $i (INDEX(.id);
    .[$i.color.id | tostring].shapes += [$i | {shape, texture}]
  ) | map(.)
' color.json shape.json

个字符
Demo

rekjcdws

rekjcdws2#

看起来你可以通过使用shape.json来获得所需的输出。
你可以使用这个(可能没有优化)过滤器来获得所需的输出:

group_by(.shape) 
    | map({ 
        id: .[0].color.id, 
        color: .[0].color.name, 
        shapes: map({ shape, texture }) 
    })

字符串
给予:

[
  {
    "id": 2,
    "color": "green",
    "shapes": [
      {
        "shape": "circle",
        "texture": "smooth"
      }
    ]
  },
  {
    "id": 1,
    "color": "red",
    "shapes": [
      {
        "shape": "square",
        "texture": "smooth"
      }
    ]
  },
  {
    "id": 3,
    "color": "blue",
    "shapes": [
      {
        "shape": "triangle",
        "texture": "smooth"
      },
      {
        "shape": "triangle",
        "texture": "rough"
      }
    ]
  }
]


Online demo

相关问题