jq 从其他key中找到value对应的值

jq 从其他key中找到value对应的值

我有一个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 [email protected]",
      "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 [email protected]"

我尝试了命令:

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

但只收到“name”键的值

答案1

用于jq选择数组中具有等于的public_key数组元素的条目(其中字符串由在命令行上导入变量的值给出):ssh_keysnameUser's keyUser's keyjq$queryname

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

-r使得该值被打印解码。如果没有-r,您将得到一个 JSON 编码(并引用)的值。

curl您可以通过上述命令传输 JSON 输出。使用给定的文档作为输入,这将生成单行

ssh-rsa AAAA [email protected]

相关内容