Demian Glait Demian Glait - 3 months ago 23
JSON Question

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

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

Answer

You can wrap the results from select in an array:

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

Output:

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