merge two lists within a object conditionally

六眼飞鱼酱① 提交于 2020-04-16 03:05:34

问题


Hellow jq experts!

I'm a jq learner and have a json obect composed lists as follows:

{
  "image_files": [
    {
      "id": "img_0001",
      "width": 32,
      "heigt": 32,
      "file_name": "img_0001.png"
    },
    {
      "id": "img_0002",
      "width": 128,
      "heigt": 32,
      "file_name": "img_0002.png"
    },
    {
      "id": "img_0003",
      "width": 32,
      "heigt": 32,
      "file_name": "img_0003.png"
    },
    {
      "id": "img_0004",
      "width": 160,
      "heigt": 32,
      "file_name": "img_0004.png"
    }
  ],
  "annotations": [
    {
      "id": "ann_0001",
      "image_id": "img_0001",
      "label": "A",
      "attributes": {
        "type": "letter",
        "augmented": false
      }
    },
    {
      "id": "ann_0002",
      "image_id": "img_0002",
      "label": "Good",
      "attributes": {
        "type": "word",
        "augmented": false
      }
    },
    {
      "id": "ann_0003",
      "image_id": "img_0003",
      "label": "C",
      "attributes": {
        "type": "letter",
        "augmented": false
      }
    },
    {
      "id": "ann_0004",
      "image_id": "img_0004",
      "label": "Hello",
      "attributes": {
        "type": "word",
        "augmented": false
      }
    }
  ]
}
  • image_id in the annotations list are foreign key referencing the id in the image_files list.

I want to join image_files and annotations with condition of annotations.attribute.type == "letter".

Expecting following ouptut:

{
  "letter_image_files_with_label": [
    {
      "id": "img_0001",
      "width": 32,
      "heigt": 32,
      "file_name": "img_0001.png",
      "label": "A"
    },
    {
      "id": "img_0003",
      "width": 32,
      "heigt": 32,
      "file_name": "img_0003.png",
      "label": "C"
    }
  ]
}

How can I produce above result from the json data input? join explained in jq manual does not seem to use this kind task. Is there a way for this? Please show me the rope.

Thanks for your generous reading.


回答1:


Indexing image_files with ids makes this pretty trivial.

INDEX(.image_files[]; .id) as $imgs | [
  .annotations[]
  | select(.attributes.type == "letter")
  | $imgs[.image_id] + {label: .label}
]

Online demo



来源:https://stackoverflow.com/questions/60967575/merge-two-lists-within-a-object-conditionally

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!