Curl

jq 從其他鍵中找到值對應的值

  • June 10, 2021

我有一個 curl | 的輸出 jq:

{
 "ssh_keys": [
   {
     "id": 30482248,
     "fingerprint": "21:57:08:d8:41:0f:89:57:0b:96:95:64:ff:59:50:69",
     "public_key": "ssh-rsa AAAA vyacheslav@MacBook.local",
     "name": "User's key"
   },
   {
     "id": 30450573,
     "fingerprint": "27:0c:2e:34:63:00:13:9d:5c:26:44:15:f0:cf:15:13",
     "public_key": "ssh-rsa AAAA-VirtualBox",
     "name": "test1"
   },
   {
     "id": 30485316,
     "fingerprint": "28:63:11:6b:a0:c7:ae:e1:e7:98:0b:01:96:c2:f4:87",
     "public_key": "ssh-rsa AAAA lessons",
     "name": "rbm-mykey"
   }
 ],
 "links": {
   "pages": {
     "last": "https://api.digitalocean.com/v2/account/keys?page=3",
     "next": "https://api.digitalocean.com/v2/account/keys?page=2"
   }
 },
  "meta": {
    "total": 59
 }
}

我想從“name”鍵返回具有“User’s key”值的“public_key”,所以結果應該是

"ssh-rsa AAAA vyacheslav@MacBook.local"

我嘗試了命令:

curl -X GET -H "Authorization: Bearer " "https://api.digitalocean.com/v2/account/keys?page=1" | jq '.[] | .[] | .name' 

但只收到“名稱”鍵的值

jq用於為數組的數組元素選擇具有等於的public_key條目(其中字元串由導入到命令行變數中的值給出):ssh_keys``name``User's key``User's key``jq``$queryname

jq -r --arg queryname "User's key" '.ssh_keys[] | select(.name == $queryname).public_key'

使-r值被列印解碼。如果沒有-r,您將返回一個 JSON 編碼(和引用)的值。

您將curl通過上述命令管道化 JSON 輸出。將給定的文件作為輸入,這將生成單行

ssh-rsa AAAA vyacheslav@MacBook.local

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