shell处理curl返回数据,在Linux Bash中从cURL获取JSON值
I want to GET some json data from a server. I do this using:
UPDATE=$(curl -i -H "Accept: application/json" -H "Content-Type: application/json" --cookie "${COOKIE_NAME}" "${1}/update/${DEVICE_NAME}");
Before this, the server is authenticated. The ${1} is the server domain, ${DEVICE_NAME} is the name of the device requesting the update.
This returns a JSON as follows:
[{"_id":"54ff35887d8ef574029b9166","user":"54fe4313883bcec2c0ac0d64","__v":0,"created":"2015-03-10T18:18:48.023Z","status":"available","pbo_udid":"lemaker","installation_script":"","description":"Prints
hello world to
console","package_name":"helloworld_1.0-1.deb","name":"Hello World
V1"}]
I want to now do 2 things:
Make sure data is returned (if no update is available, the server returns []
Extract data, for instance package_name
How do I do these in Linux bash script?
解决方案
Assuming there's no nested array:
cat <
sed -rne '/:/s@^\s+"(\w+)":\s+"([^"]+)",?@json_\1="\2"@gp'
[{"_id":"54ff35887d8ef574029b9166","user":"54fe4313883bcec2c0ac0d64","__v":0,"created":"2015-03-10T18:18:48.023Z","status":"available","pbo_udid":"lemaker","installation_script":"","description":"Prints hello world to console","package_name":"helloworld_1.0-1.deb","name":"Hello World V1"}]
EOF
returns
json__id="54ff35887d8ef574029b9166"
json_user="54fe4313883bcec2c0ac0d64"
json_created="2015-03-10T18:18:48.023Z"
json_status="available"
json_pbo_udid="lemaker"
json_description="Prints hello world to console"
json_package_name="helloworld_1.0-1.deb"
json_name="Hello World V1"
You need json_reformat for this to work.
EDIT : without json_reformat:
cat <
sed -re 's@(\[|\]|\{|\})@@g' -e 's/,/\n/g' | \
sed -re 's@"(\w+)":\s*"?([^"]*)"?@json_\1="\2"@g'
[{"_id":"54ff35887d8ef574029b9166","user":"54fe4313883bcec2c0ac0d64","__v":0,"created":"2015-03-10T18:18:48.023Z","status":"available","pbo_udid":"lemaker","installation_script":"","description":"Prints hello world to console","package_name":"helloworld_1.0-1.deb","name":"Hello World V1"}]
EOF
It returns (note the version number that is reformatted anyway):
json__id="54ff35887d8ef574029b9166"
json_user="54fe4313883bcec2c0ac0d64"
json___v="0"
json_created="2015-03-10T18:18:48.023Z"
json_status="available"
json_pbo_udid="lemaker"
json_installation_script=""
json_description="Prints hello world to console"
json_package_name="helloworld_1.0-1.deb"
json_name="Hello World V1"
You can now try parsing this text using eval or source it from stdin.
更多推荐
所有评论(0)