在Linux Bash中从cURL获取JSON值

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

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

在此之前,服务器已通过身份validation。 ${1}是服务器域, ${DEVICE_NAME}是请求更新的设备的名称。

这将返回一个JSON,如下所示:

[{ “_id”: “54ff35887d8ef574029b9166”, “用户”: “54fe4313883bcec2c0ac0d64”, “__ V”:0, “创build”: “2015-03-10T18:18:48.023Z”, “状态”: “可用的”,” “hello world”,“package_name”:“helloworld_1.0-1.deb”,“name”:“Hello World V1”} ]

我想现在做2件事情:

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

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

假设没有嵌套的数组:

 cat <<EOF | json_reformat | \ 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 

回报

 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_\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 

它返回(注意无论如何重新格式化的版本号):

 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解析这个文本,或者从stdin来源。

使用jq或jsawk更容易和可靠地完成:

 content=$(curl ...) package_name=$(jq -r '.package_name' <<<"$content")