我的 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"
}
}
我的 key 会不时更改。因此,例如 20160522201409-jobsv1-1
明天可能是其他内容。此外,我可能在 json 负载中有多个这样的条目。
我想 echo $KEYS
并且我正在尝试使用 jq
来做到这一点。
我尝试过的事情:
| jq .KEYS
是我经常使用的命令。
有没有jq命令显示json中的所有主键?
我只关心hostname
字段。我想把它提取出来。我知道如何使用 grep
来做到这一点,但这不是一种干净的方法。
最佳答案
您可以简单地使用:键
:
% 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.
如果你想要一个未知属性下的已知值,例如 xxx.hostName
:
% jq -r '.[].hostName' my.json
20160522201409-jobsv1-1
关于json - 如何使用 `jq`获取 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37577683/