首页 > 其他分享 >解析curl的 json 响应 并赋值

解析curl的 json 响应 并赋值

时间:2023-01-06 17:13:48浏览次数:38  
标签:sys json result https curl com 赋值

you can use python , which exists in all linux based systems , to parse the json for you

https://askubuntu.com/questions/714458/bash-script-store-curl-output-in-variable-then-format-against-string-in-va

To store the result of curl in a variable:

ipinfo=$(curl ipinfo.io/8.8.8.8)
curl ipinfo.io/"8.8.8.8" 2>/dev/null |
python -c 'import json,sys;
result=json.load(sys.stdin);
print(result["'city'"] + ", " + result["'region'"])';

最推荐用jq 没有就用python

https://stackoverflow.com/questions/1955505/parsing-json-with-unix-tools

curl -s 'https://api.github.com/users/lambda' | jq -r '.name'


You can also do this with tools that are likely already installed on your system, like Python using the json module, and so avoid any extra dependencies, while still having the benefit of a proper JSON parser. The following assume you want to use UTF-8, which the original JSON should be encoded in and is what most modern terminals use as well:
Python 3:

curl -s 'https://api.github.com/users/lambda' | \
python3 -c "import sys, json; print(json.load(sys.stdin)['name'])"

Python 2:

export PYTHONIOENCODING=utf8
curl -s 'https://api.github.com/users/lambda' | \
python2 -c "import sys, json; print json.load(sys.stdin)['name']"

 

标签:sys,json,result,https,curl,com,赋值
From: https://www.cnblogs.com/lbzwd/p/17031013.html

相关文章