0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
JohnDorian
  • 21
  • 1
  • 7
  • Possible duplicate of [Parsing JSON with Unix tools](https://stackoverflow.com/questions/1955505/parsing-json-with-unix-tools) – Allan Dec 26 '17 at 01:17

2 Answers2

0

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"
oshirogo
  • 21
  • 1
0

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/

Viktor Khilin
  • 1,760
  • 9
  • 21