curl命令为我提供了JSON输出,如下所示:-[{"Description":"","Value":"bc","Key":"a"},{"Description":"","Value":"ef","Key":"d"},...]
现在,我只想捕获“键”和“值”的值,以使其在执行echo $a
时给出“ bc”,echo $d
时给出“ ef”等
注意:我绝对是shell脚本/ bash的新手,因此这个问题
提前谢谢
答案 0 :(得分:1)
您可以使用jq
来解析数组并获取必要的值。
echo '[{"Description":"","Value":"bc","Key":"a"},{"Description":"","Value":"ef","Key":"d"}]' | jq '.[] | select(.Key == "d").Value'
这应该给您“ ef”,并且
echo '[{"Description":"","Value":"bc","Key":"a"},{"Description":"","Value":"ef","Key":"d"}]' | jq '.[] | select(.Key == "a").Value'
会给您“ bc”
您可以使用curl语句替换echo
。
有关jq的更多信息:https://stedolan.github.io/jq/
答案 1 :(得分:0)
类似的事情可能会起作用:
dataString='[{"Description":"","Value":"bc","Key":"a"},{"Description":"","Value":"ef","Key":"d"},...]'
while read value key; do
echo "key: '$key', value : '$value'"
done < <(echo "$dataString" | sed 's/},{/\n/g' | tr -d '[]{}"' | tr ':' ',' | cut -d',' -f 4,6 --output-delimiter=' ')
详细信息:
dataString
是curl
整个(echo "$dataString"....)
只需将$dataString
变成:
bc a
ef d
<(...)
构造是process substitution。它允许使用与从文件读取相同的方法读取命令的输出