Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

jq

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 
like image 438
Demian Glait Avatar asked Jul 21 '16 09:07

Demian Glait


People also ask

Does jq use JSONPath?

JSONPath distinguishes between the "root object or element" ($) and "the current object or element" (.). jq simply uses . to refer to the current JSON entity and so it is context-dependent: it can refer to items in the input stream of the jq process as a whole, or to the output of a filter.

What is jq JSON parser?

jq is a command-line tool for parsing JSON. Most of the popular API and data services use the JSON data format, so we'll learn how it's used to serialize interesting information, and how to use the jq to parse it at the command-line.

What is jq filter?

A jq program is a "filter": it takes an input, and produces an output. There are a lot of builtin filters for extracting a particular field of an object, or converting a number to a string, or various other standard tasks.


2 Answers

You can wrap the results from select in an array:

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

Output:

{   "a": "x",   "b": false } 
like image 57
hek2mgl Avatar answered Oct 05 '22 04:10

hek2mgl


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 } 
like image 26
jq170727 Avatar answered Oct 05 '22 05:10

jq170727