shell解析json

shell解析json

以下是几种不同的方法来在shell中解析JSON:

  1. 使用awk命令和正则表达式:
json='{"name":"John","age":30,"city":"New York"}'
key='age'
value=$(echo $json | awk -v k="$key" 'BEGIN{RS=","; FS=":"} $1 ~ "\""k"\""{gsub(/[{}"]/,"",$2); print $2}')
echo $value

         2.使用awk命令和正则表达式:

json='{"name":"John","age":30,"city":"New York"}'
key='age'
value=$(echo $json | jq -r .$key)
echo $value

        3. 使用Python和jq库:

json='{"name":"John","age":30,"city":"New York"}'
key='age'
value=$(echo $json | python -c 'import json,sys; data=json.load(sys.stdin); print data["'$key'"]')
echo $value

 

 
posted @ 2024-09-09 17:47  苹果芒  阅读(406)  评论(0编辑  收藏  举报