获取 jq json 解析中的第一个(或第 n 个)元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38500363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:30:49  来源:igfitidea点击:

get the first (or n'th) element in a jq json parsing

jsonjq

提问by Demian Glait

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

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

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

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?

但是,如果 json 已经被反汇编(例如,在使用“select”过滤条目之后),我该如何选择单个条目并避免出现此处的错误?

$ 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

回答by hek2mgl

You can wrap the results from selectin an array:

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

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

Output:

输出:

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

回答by jq170727

jq also provides first/0, last/0, nth/1so in this case the filter

jq 还提供first/0, last/0nth/1所以在这种情况下过滤器

  ( map(select(.a == "x")) | first  )
, ( map(select(.a == "x")) | last   ) 
, ( map(select(.a == "x")) | nth(1) )

produces

产生

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

Additional streaming forms 'first/1', 'last/1'and 'nth/2'are also available so with this data

其他流形式'first/1''last/1''nth/2'也可用,因此使用此数据

  ( first(.[]  | select(.a == "x")) )   
, ( last(.[]   | select(.a == "x")) )
, ( nth(1; .[] | select(.a == "x")) )

produces

产生

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

回答by tink

use map

map

cat raw.json|jq -r -c 'map(select(.a=="x"))|.[1]'

maprecivce a filterto filter an array.

map接收一个过滤器来过滤一个数组。

this command

这个命令

cat raw.json|jq -r -c 'map(select(.a=="x"))'

give the middle result

给出中间结果

[{"a":"x","b":true},{"a":"x","b":false}]

[{"a":"x","b":true},{"a":"x","b":false}]

.[1]take the first element

.[1]取第一个元素