在Bash中从JSON中提取特定值

问题描述 投票:0回答:2

我试图从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字符串中提取精确值的最佳方法是什么?

json bash api variables
2个回答
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"

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 jqapt-get install jq

jq手册在这里:https://stedolan.github.io/jq/manual/

© www.soinside.com 2019 - 2024. All rights reserved.