Reputation: 21
I an trying to extract one specific value from a JSON string. The string looks like this:
{"801":{"170":{"100":"25.12.17 23:38:30","101":0,"102":0,"103":0,"104":0,"105":400,"106":200,"107":51100,"108":5329700,"109":17596300,"110":0,"111":0,"112":0,"113":0,"114":0,"115":0,"116":5500}}}
I am trying to put the value behind "105" (400 in this example) in a variable. I have tried the following:
wget -qO- --post-data='{"801":{"170":null}}' http://192.168.1.11/getjp \
|sed -e 's/[{},]/\n/g' \
| stroom=$ awk -F : '
{if($1=="\"105\"") {print $2}};
This prints the value I want (400) but the variable is empty.
What is the best way to extract that exact value from the JSON string?
Upvotes: 0
Views: 555
Reputation: 1838
You'd better use jq:
wget -qO- --post-data='{"801":{"170":null}}' http://192.168.1.11/getjp \
| jq '."801" | to_entries[] | [{"key": .key, "value": .value."105"}]' \
| grep value | awk '{print $2}'
Easier:
wget -qO- --post-data='{"801":{"170":null}}' http://192.168.1.11/getjp \
| jq '."801" | ."170" | ."105"'
Result as variable:
variable=$(wget -qO- --post-data='{"801":{"170":null}}' http://192.168.1.11/getjp \
| jq '."801" | ."170" | ."105"')
echo ${variable}
400
Install it: yum -y install jq
or apt-get install jq
jq manual available here: https://stedolan.github.io/jq/manual/
Upvotes: 1
Reputation: 21
As alluded to here, using a tool like Python is a great way to manipulate JSON. In your example:
data='{"801":{"170":{"100":"25.12.17 23:38:30","101":0,"102":0,"103":0,"104":0,"105":400,"106":200,"107":51100,"108":5329700,"109":17596300,"110":0,"111":0,"112":0,"113":0,"114":0,"115":0,"116":5500}}}'
res=`echo $data | python -c "import sys, json; print json.load(sys.stdin)['801']['170']['105']"`
echo "Result: $res"
#Prints "Result: 400"
Upvotes: 0