Linux

JQ Linux JSON解析未知密鑰

  • April 24, 2019

我想建構一個自動化腳本,在 vultr.com 頁面上建構一個新的 VPS 伺服器。他們也有一個 API 訪問,我可以創建它並接收我需要的任何東西。問題是,vultr 會發送一個帶有數字作為每個 VPS 伺服器密鑰的響應。我使用此命令創建 VPS 並獲取伺服器編號:

idofserver=$(curl -H 'API-KEY: "HERE IS MY PRIVATE API KEY"' \
            https://api.vultr.com/v1/server/create \
           --data 'DCID=9' --data 'VPSPLANID=201' --data 'OSID=244' \
           | jq '."SUBID"' | /bin/sed 's/"//g')

它還給了我沒有“的數字。所以命令行中的響應看起來像:2342738。變數也變成了數字。因為當我輸入“echo $idofserver”時,我得到了數字 2342738 .

在該行之後,我在一個循環中執行該命令:

echo "VULRT IS WORKING ID: $idofserver"
response=$(curl -H 'API-KEY: "HERE IS MY PRIVATE API KEY"' \
          https://api.vultr.com/v1/server/list 100>/dev/null)
status=$(echo "$response" | jq '."$idofserver"' | jq '."status"')

它還返回“VULTR 正在工作 ID:2342738”。但它保持在一個完整的循環中,因為它不會將變數 $status 更改為活動狀態。while 循環條件是:while [ $status != "active" ]; do

我手動嘗試了響應響應並jq使用 $status 上方的命令將其發送出去。但有回應:“空”。我不知道為什麼。

以下是 VULTR 中 JSON 響應的樣子:

{"2342738":{"SUBID":"2342738","os":"Debian 9 x64 (stretch)","ram":"1024 MB","disk":"Virtual 25 GB","main_ip":"11.11.11.11","vcpu_count":"1","location":"Frankfurt","DCID":"9","default_password":"=*{#?HHH*!-(","date_created":"2019-04-22 17:49:28","pending_charges":"0.01","status":"active","cost_per_month":"5.00","current_bandwidth_gb":0,"allowed_bandwidth_gb":"1000","netmask_v4":"255.255.0.0","gateway_v4":"11.11.11.11","power_status":"running","server_state":"installingbooting","VPSPLANID":"201","v6_main_ip":"","v6_network_size":"","v6_network":"","v6_networks":[],"label":"","internal_ip":"","kvm_url":"https:\/\/my.vultr.com\/subs\/vps\/novnc\/api.php?data=jhkjhjhkjhkj","auto_backups":"no","tag":"","OSID":"244","APPID":"0","FIREWALLGROUPID":"0"}}

首先,使用-rwithjq來獲取原始數據。不要通過輸出sed

url='https://api.vultr.com/v1/server'
key='API-KEY: "HERE IS MY PRIVATE API KEY"'

serverid=$( curl -H "$key" "$url/create" \
               --data 'DCID=9' \
               --data 'VPSPLANID=201' \
               --data 'OSID=244' |
           jq -r '.SUBID' )

然後,第二次呼叫jq將不起作用,因為您在表達式周圍使用單引號,這會阻止 shell 變數擴展。但是,這不是將 shell 變數傳遞到jq.

反而:

printf 'VULRT IS WORKING ID: %s\n' "$serverid"

status=$( curl -s -H "$key" "$url/list" 100 |
         jq -r --arg id "$serverid" '.[$id].status' )

Using--arg id "$serverid"將創建一個jq變數,您可以通過 訪問其值$id。要將其用作鍵,請使用[$id].

我還冒昧地根據我自己的個人喜好更改了程式碼中的其他一些內容。

引用自:https://unix.stackexchange.com/questions/513883