如何使用`jq`获取密钥

How to use `jq` to obtain the keys

我的 json 看起来像这样:

{
  "20160522201409-jobsv1-1": {
    "vmStateDisplayName": "Ready",
    "servers": {
      "20160522201409 jobs_v1 1": {
        "serverStateDisplayName": "Ready",
        "creationDate": "2016-05-22T20:14:22.000+0000",
        "state": "READY",
        "provisionStatus": "PENDING",
        "serverRole": "ROLE",
        "serverType": "SERVER",
        "serverName": "20160522201409 jobs_v1 1",
        "serverId": 2902
      }
    },
    "isAdminNode": true,
    "creationDate": "2016-05-22T20:14:23.000+0000",
    "totalStorage": 15360,
    "shapeId": "ot1",
    "state": "READY",
    "vmId": 4353,
    "hostName": "20160522201409-jobsv1-1",
    "label": "20160522201409 jobs_v1 ADMIN_SERVER 1",
    "ipAddress": "10.252.159.39",
    "publicIpAddress": "10.252.159.39",
    "usageType": "ADMIN_SERVER",
    "role": "ADMIN_SERVER",
    "componentType": "jobs_v1"
  }
}

我的密钥会不时更改。因此,例如 20160522201409-jobsv1-1 明天可能是其他内容。此外,我可能在 json 有效负载中有多个这样的条目。

我想 echo $KEYS 并且正在尝试使用 jq

我尝试过的事情: | jq .KEYS 是我经常使用的命令。

有没有jq命令显示json中的所有主键?

我只关心 hostname 字段。我想把它提取出来。我知道如何使用 grep 来做到这一点,但这不是一个干净的方法。

您可以简单地使用:keys:

% jq 'keys' my.json
[
  "20160522201409-jobsv1-1"
]

并获得第一:

% jq -r 'keys[0]' my.json
20160522201409-jobsv1-1

-r 用于原始输出:

--raw-output / -r: With this option, if the filter’s result is a string then it will be written directly to standard output rather than being formatted as a JSON string with quotes. This can be useful for making jq filters talk to non-JSON-based systems.

Source

如果您想要一个低于未知值的已知值 属性,例如 xxx.hostName:

% jq -r '.[].hostName' my.json
20160522201409-jobsv1-1