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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值