首页 > 解决方案 > 合并一个对象中的两个列表,包括长度检查

问题描述

您好jq用户和专家,

仅供参考,这个问题与有条件地合并一个对象中的两个列表有关。但是当前的问题是与两个没有联合条件的列表合并,包括长度检查。

对于json数据如下:

{
  "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_filesannotations具有联合条件

最终结果应如下所示:

{
  "four_letter_word_image_files_with_label": [
    {
      "id": "img_0002",
      "width": 128,
      "heigt": 32,
      "file_name": "img_0004.png"
      "label": "Good"
    }
  ]
}

How can I produce above result from the json data input?

Thanks for your reading.

标签: mergeconditional-statementsjq

解决方案


这是一个帮助您入门的功能。您可以扩展它以满足您的需求。

def Hongsoog:
  def makemap: reduce .annotations[] as $item ({}; .[$item.image_id]=$item) ;
  def join:    makemap as $idx | [ .image_files[] | { i:., a: $idx[.id] } ] ;
  def isword:  .a.attributes.type == "word" ;
  def islen4:  .a.label | length == 4 ;
  def format:  .i.label = .a.label | .i ; 
  def result:  [ join[] | select(isword and islen4) | format ];
  {
    "four_letter_word_image_files_with_label": result
  };

Hongsoog

在线尝试!


推荐阅读