bash 如何使用`jq`获取密钥
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37577683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use `jq` to obtain the keys
提问by sudhishkr
My json looks like this :
我的 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"
}
}
My key keeps changing from time to time. So for example 20160522201409-jobsv1-1
may be something else tomorrow. Also I may more than one such entry in the json payload.
我的钥匙不时变化。例如,20160522201409-jobsv1-1
明天可能是其他事情。此外,我可能会在 json 负载中出现多个这样的条目。
I want to echo $KEYS
and I am trying to do it using jq
.
我想要echo $KEYS
并且我正在尝试使用jq
.
Things I have tried :
| jq .KEYS
is the command i use frequently.
我尝试过的事情:
| jq .KEYS
是我经常使用的命令。
Is there a jq command to display all the primary keys in the json?
是否有 jq 命令来显示 json 中的所有主键?
I only care about the hostname
field. And I would like to extract that out. I know how to do it using grep
but it is NOT a clean approach.
我只关心hostname
领域。我想把它提取出来。我知道如何使用grep
它,但这不是一种干净的方法。
回答by andlrc
You can simply use: keys
:
您可以简单地使用keys
::
% jq 'keys' my.json
[
"20160522201409-jobsv1-1"
]
And to get the first:
并获得第一个:
% jq -r 'keys[0]' my.json
20160522201409-jobsv1-1
-r
is for raw output:
-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.
--raw-output / -r:
使用此选项,如果过滤器的结果是字符串,则它将直接写入标准输出,而不是格式化为带引号的 JSON 字符串。这对于使 jq 过滤器与非基于 JSON 的系统通信非常有用。
If you want a known value below an unknown property, eg xxx.hostName
:
如果您希望在未知属性下方有一个已知值,例如xxx.hostName
:
% jq -r '.[].hostName' my.json
20160522201409-jobsv1-1