从 Linux Bash 中的 cURL 获取 JSON 值

Getting JSON value from cURL in Linux Bash

我想 GET 从服务器获取一些 json 数据。我这样做使用:

UPDATE=$(curl -i -H "Accept: application/json" -H "Content-Type: application/json" --cookie "${COOKIE_NAME}" "/update/${DEVICE_NAME}");

在此之前,服务器已通过身份验证。 </code> 是服务器域,<code>${DEVICE_NAME} 是请求更新的设备名称。

这个returns一个JSON如下:

[{"_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"}]

我现在想做两件事:

  1. 确保返回数据(如果没有更新可用,服务器 returns []
  2. 提取数据,例如package_name

如何在 Linux bash 脚本中执行这些操作?

假设没有嵌套数组:

cat <<EOF | json_reformat | \
    sed -rne '/:/s@^\s+"(\w+)":\s+"([^"]+)",?@json_=""@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"

你需要 json_reformat 才能正常工作。

编辑 : 没有 json_reformat:

cat <<EOF | \
    sed -re 's@(\[|\]|\{|\})@@g' -e 's/,/\n/g' | \
    sed -re 's@"(\w+)":\s*"?([^"]*)"?@json_=""@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

它returns(注意重新格式化的版本号):

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"

您现在可以尝试使用 eval 或从标准输入中获取它来解析此文本。

使用 jq or jsawk:

更容易和更可靠地完成
content=$(curl ...)
package_name=$(jq -r '.package_name' <<<"$content")