在JQ中选择包含数组

时间:2019-01-23 19:23:41

标签: json select jq

我想使用Contains从数组中选择特定项目,并使用JQ获取第一个项目。

JQ:

  .amazon.items[] | select(.name | contains ("shoes")) 

JSON:

  {
    "amazon": {
      "activeitem": 2,
      "items": [
        {
          "id": 1,
          "name": "harry potter",
          "state": "sold"
        },
        {
          "id": 2,
          "name": "adidas shoes",
          "state": "in inventory"
        },
        {
          "id": 3,
          "name": "watch",
          "state": "returned"
        },{
          "id": 4,
          "name": "adidas shoes",
          "state": "in inventory"
        }
      ]
    }
  } 

预期结果:

    {
      "activeitem": 2,
      "item": {
        "id": 2,
        "name": "adidas shoes",
        "state": "in inventory"
      }
    }

实际:

尝试了各种选项,例如但未获得预期的响应。

  1. .amazon.items [] | select(.name |包含(“鞋子”))
  2. .amazon.items | select(。[]。name |包含(“鞋子”))| 。[0]

另外,当我尝试组合activeitem和Item时,我得到类似这样的信息,这也是错误的。

    {
      "activeitem": 2,
      "item": {
        "id": 2,
        "name": "adidas shoes",
        "state": "in inventory"
      }
    },
      {
      "activeitem": 2,
      "item": {
        "id": 2,
        "name": "adidas shoes",
        "state": "in inventory"
      }
    }

1 个答案:

答案 0 :(得分:2)

要编辑“就地”,您可以编写:

.amazon
| .items |= map(select(.name | contains ("shoes")))[0]

如果您确实想将名称“ items”更改为“ item”,则可以对上述内容进行如下调整:

.amazon
| .item = (.items | map(select(.name | contains ("shoes")))[0])
| del(.items)