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
Looks like you want the following :
jq --raw-output '.items[] | .node + " " + .result.stdout' out.json
You can try it here
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With