Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract fields from a json string using jq

Tags:

json

bash

jq

How to extract two fields from a JSON file using jq?

When I run 'jq '.node' out.json I get the word 'null' in output

Here is what I have in a file named out.json

head out.json 
{ "items": [ {"node":"aaaa-cn001.me.com","status":"success","result":{"stdout":"3.10.0-957.12.1.el7.x86_64\n","stderr":"","exit_code":0}} , {"node":"aaaa-cn002.me.com","status":"success","result":{"stdout":"3.10.0-957.10.1.el7.x86_64\n","stderr":"","exit_code":0}} , {"node":"aaaa-cn003.me.com","status":"success","result":{"stdout":"3.10.0-957.10.1.el7.x86_64\n","stderr":"","exit_code":0}} , {"node":"aaaa-cn004.me.com","status":"success","result":{"stdout":"3.10.0-957.12.1.el7.x86_64\n","stderr":"","exit_code":0}}

I would like the output to be this way:

aaaa-cn001.me.com 3.10.0-957.12.1.el7.x86_64
aaaa-cn002.me.com 3.10.0-957.10.1.el7.x86_64
aaaa-cn003.me.com 3.10.0-957.10.1.el7.x86_64
aaaa-cn004.me.com 3.10.0-957.12.1.el7.x86_64
like image 771
rony thomas Avatar asked Dec 18 '22 17:12

rony thomas


2 Answers

Looks like you want the following :

jq --raw-output '.items[] | .node + " " + .result.stdout' out.json

You can try it here

like image 192
Aaron Avatar answered Dec 20 '22 06:12

Aaron


if interested in an alternative solution, there's anoter way of achieving the same - using a walk-path based unix utility jtc:

bash $ <out.json jtc -w'[items][:][node]<n>v[-1][result][stdout]' -T'"{n} {}"' -qq
aaaa-cn001.me.com 3.10.0-957.12.1.el7.x86_64

aaaa-cn002.me.com 3.10.0-957.10.1.el7.x86_64

aaaa-cn003.me.com 3.10.0-957.10.1.el7.x86_64

aaaa-cn004.me.com 3.10.0-957.12.1.el7.x86_64

bash $ 

Note, an extra line occurs here, because stdout values carry trailing \n, which upon unquoting JSON string (-qq) results in the extra spacer.

If you like to print w/o preserving that line, use this form then:

bash $ <out.json jtc -w'[items][:][node]<n>v[-1][result][stdout]:<(.*)\\n>R' -T'"{n} {$1}"' -qq
aaaa-cn001.me.com 3.10.0-957.12.1.el7.x86_64
aaaa-cn002.me.com 3.10.0-957.10.1.el7.x86_64
aaaa-cn003.me.com 3.10.0-957.10.1.el7.x86_64
aaaa-cn004.me.com 3.10.0-957.12.1.el7.x86_64
bash $ 

PS> Disclosure: I'm the creator of the jtc - shell cli tool for JSON operations

like image 39
Dmitry Avatar answered Dec 20 '22 06:12

Dmitry