获取jq json解析中的第一个(或第n个)元素 [英] get the first (or n'th) element in a jq json parsing

查看:140
本文介绍了获取jq json解析中的第一个(或第n个)元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在[]内的json中获取第一个元素

I can get the 1st element in a json inside []

$ echo '[{"a":"x", "b":true}, {"a":"XML", "b":false}]' | jq '.[1]'
{
  "a": "XML",
  "b": false
}

但是,如果json已经被分解(例如,使用'select'过滤条目之后),我该如何选择一个条目并避免此处看到的错误?

But if the json is already disassembled (for instance, after filtering entries using 'select'), how can I choose a single entry and avoid the error seen here?

$ echo '[{"a":"x", "b":true}, {"a":"x", "b":false},{"a":"XML", "b":false}]' | jq '.[] | select( .a == "x")'
{
  "a": "x",
  "b": true
}
{
  "a": "x",
  "b": false
}
$ echo '[{"a":"x", "b":true}, {"a":"x", "b":false},{"a":"XML", "b":false}]' | jq '.[] | select( .a == "x") | .[1]'
jq: error (at <stdin>:1): Cannot index object with number

推荐答案

您可以将select的结果包装在数组中:

You can wrap the results from select in an array:

jq '[.[]|select(.a=="x")][0]' your.json

输出:

{
  "a": "x",
  "b": false
}

这篇关于获取jq json解析中的第一个(或第n个)元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆