Let's go through json with jq

I am parsing an API that sends me a JSON response as follows:

{ "newList": { "243": { "id": "243", "name": "test", "create": { "date": "2017-08-31 13:57:29" } }, "244": { "id": "244", "name": "test", "create": { "date": "2017-08-31 13:57:29" } } } } 

I am trying to get the name and creation date from this using bash with jq, so almost nothing came of it.

jq '.newList' works and takes me to the same level, but this is not enough.

jq '.newList.243' gives me a compilation error. In addition, 243 is dynamic and can change at any time. What am I doing wrong here?

+4
source share
1 answer

Assuming your root name is node newList , as you have in the question newList , to get the id and the created date, you can do string interpolation with jq

 api-producing-json | jq --raw-output '.newList[] | "\(.id) \(.create.date)"' 

Thus, the filter does not depend on dynamic numbers in nodes ( 243 , 244 ). Leave the --raw-output flag if you need output with quotes.

To continue the process in a loop, you can iterate over the bash loop,

 while read -r id name date; do echo "Do whatever with ${id} ${name} ${date}" done< <(api-producing-json | jq --raw-output '.newList[] | "\(.id) \(.name) \(.create.date)"') 

or even more carefully distinguish between words, if you are worried about spaces in any of the fields, use a separator like | in the filter as "\(.id)|\(.name)|\(.create.date)" and use the read command in the while loop set IFS=| so that the variables are saved accordingly.


Always use official jq - documentation for reference and use this pretty site to test filters, jq - online

+5
source

Source: https://habr.com/ru/post/1275106/


All Articles