json jq -如果嵌套dict的第n个元素匹配,则选择一个项

xoefb8l8  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(90)

我有一个像这样的行分隔的JSON数据:

[
  {
    "id": 671731542,
    "type": "BeReq",
    "records": [
      { "tag": "foo", "value": "bar" },
      { "tag": "foo", "value": "bar" },
      { "tag": "RespStatus", "value": "200" },
      { "tag": "RespReason", "value": "OK" },
      { "tag": "foo", "value": "bar" },
      { "tag": "RespStatus", "value": "304" },
      { "tag": "RespReason", "value": "Not Modified" }
    ]
  }
]
[
  {
    "id": 671731543,
    "type": "BeReq",
    "records": [
      { "tag": "foo", "value": "bar" },
      { "tag": "foo", "value": "bar" },
      { "tag": "RespStatus", "value": "200" },
      { "tag": "RespReason", "value": "OK" }
    ]
  }
]

字符串
我希望能够根据records数组中的第n个RespStatus进行过滤。我可以通过 anyRespStatus来过滤项目,如:

jq '.[] | select(.records[] | .tag=="RespStatus" and .value=="304")' < requests.log


但有时我需要过滤,如果只有第n个RespStatus304

uqxowvwt

uqxowvwt1#

您可以使用nth过滤器来提取符合条件的元素:

.[] | select(nth(1;.records[]|select(.tag=="RespStatus")).value=="304")

字符串
(零基)
或者,Map数组,然后按索引访问:

.[] | select(.records|map(select(.tag=="RespStatus"))[1].value=="304")


(同样是从零开始;它需要分配一个新数组)

相关问题