0

please help me.

I have the string (json request) :

{"jsonrpc":"2.0","result":[{"hostid":"10158"}],"id":1}

i try to parsing it with command :

reference_id2=`echo "$reference_id" | python -c 'import json, sys; print json.load(sys.stdin)["result"]'`

and still have [{u'hostid': u'10158'}]

How i can get only 10158 (like in example)

THanks.

P.S. this is doesn't work too :

reference_id2=`echo "$reference_id" | python -c 'import json, sys; print json.load(sys.stdin)["result"]["hostid"]'`
1
  • result is a list. You need to index into it before you can get hostid out. (The error for that second example should have tipped you off about that.) Try ...["result"][0]["hostid"]' Commented Feb 4, 2015 at 19:21

2 Answers 2

2

In your sample result is an array. To get hostid you need to specify item index:

json.load(sys.stdin)["result"][0]["hostid"]

So your code shoud be like:

reference_id2=`echo "$reference_id" | python -c 'import json, sys; print json.load(sys.stdin)["result"][0]["hostid"]'`
Sign up to request clarification or add additional context in comments.

Comments

2

Give jq a try. It's the easiest way to parse JSON in the shell.

$ jq -r '.result[0].hostid' <<< "$json"
10158

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.