【问题标题】:Selecting in JQ with Contains in a Array在 JQ 中选择包含在数组中
【发布时间】:2019-01-23 19:23:40
【问题描述】:

我想使用 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 | contains ("shoes"))
  2. .amazon.items | select(.[].name | contains ("shoes")) | .[0]

另外,当我尝试组合 activeitemitem 时,我得到了类似的结果,这也是错误的。

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

【问题讨论】:

    标签: json select jq


    【解决方案1】:

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

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

    如果您确实想将名称“items”更改为“item”,您可以按如下方式调整上述内容:

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

    【讨论】:

    • 嗨,Peak,我可以像转换到新对象一样执行此操作吗?在这里,我修剪了 JSON,输入 json 中有很多其他字段,我在输出中不需要这些字段。我可以使用 del 删除它们,但这正在成为一个大列表。
    • @Aksanth - 抱歉,我不明白这个新问题。也许您应该创建一个新问题?请不要忘记遵循minimal reproducible example 准则。
    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 2016-09-30
    • 2018-02-13
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多