【问题标题】:How to filter an array of objects based on value of a element in the Json in JQ如何根据JQ中Json中元素的值过滤对象数组
【发布时间】:2018-12-28 18:51:59
【问题描述】:

我正在尝试使用 JQ 从 Json 中获取值。

我必须从 inputJson (activeItem) 中获取一个 ID,并使用该 ID 从下面的项目列表中获取元素的名称。

这可以在单个查询中完成吗?

{
"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"
  }
]
}
}

现在我首先获取值并进行过滤,而不是我想在单个查询中进行。

【问题讨论】:

    标签: json select jq


    【解决方案1】:

    使用您的数据,过滤器:

    .amazon
    | .activeitem as $id
    | .items[]
    | select(.id == $id)
    | .name
    

    产生:

    "adidas shoes"
    

    (如果需要原始字符串,请使用 -r 命令行选项。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-29
      • 1970-01-01
      • 1970-01-01
      • 2016-11-02
      • 2019-09-05
      • 1970-01-01
      相关资源
      最近更新 更多