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

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

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

But if json is already parsed (for example, after filtering records using "select"), how can I select one record and avoid the error visible 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 
+16
source share
3 answers

You can wrap select results in an array:

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

Output:

 { "a": "x", "b": false } 
+23
source

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 stream forms 'first / 1' , 'last / 1' and 'nth / 2' are also available 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 } 
+5
source

use map

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

map get filter to filter the array.

this team

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

give an average result

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

.[1] take the first item

+1
source

All Articles