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

隐身守侯 提交于 2020-05-25 08:57:06

问题


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
}

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

回答1:


You can wrap the results from select in an array:

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

Output:

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



回答2:


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

  ( 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(.[]  | 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
}



回答3:


use map

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

map recivce a filter to filter an array.

this command

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

give the middle result

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

.[1] take the first element



来源:https://stackoverflow.com/questions/38500363/get-the-first-or-nth-element-in-a-jq-json-parsing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!