5

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
1
  • 2
    Your input isn't JSON. (You're missing ]} at the end). People answering questions are more likely to do so if they don't have to massage your sample data. Commented Jun 4, 2019 at 12:52

2 Answers 2

10

Looks like you want the following :

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

You can try it here

Sign up to request clarification or add additional context in comments.

3 Comments

Op probably wants -r as well.
@WilliamPursell --raw-output is -r's long form :)
@Aaron Thank you so much!. I can't tell you how happy I am seeing the result your command produced. You nailed it!!
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.