我试图从json字符串中提取一个特定值。字符串如下所示:
{"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}}}
我试图将值放在“105”(本例中为400)的变量中。我尝试过以下方法:
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}};
这会打印我想要的值(400),但该变量为空。
从JSON字符串中提取确切值的最佳方法是什么?
答案 0 :(得分:0)
正如here所提到的,使用像Python这样的工具是一种操纵JSON的好方法。在您的示例中:
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"
答案 1 :(得分:0)
你最好使用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}'
更容易:
wget -qO- --post-data='{"801":{"170":null}}' http://192.168.1.11/getjp \
| jq '."801" | ."170" | ."105"'
结果为变量:
variable=$(wget -qO- --post-data='{"801":{"170":null}}' http://192.168.1.11/getjp \
| jq '."801" | ."170" | ."105"')
echo ${variable}
400
安装它:yum -y install jq
或apt-get install jq
jq手册可在此处获取:https://stedolan.github.io/jq/manual/