jq:根据键是否以指定的字符串结尾来过滤输入 [英] jq: filter input based on if key ends with specified string
问题描述
我收到了这个JSON数据混乱的消息,我需要提取类型列表:
I get this JSON data mess in and I need to extract the list of types:
{
"token/": {
"accessor": "auth_token_909d6a81",
"config": {
"default_lease_ttl": 0,
"max_lease_ttl": 0
},
"description": "token based credentials",
"local": false,
"seal_wrap": false,
"type": "token" <-- I need to extract this value ...
},
"userpass/": {
"similar_to": {
"above": null
},
"description": "",
"local": false,
"seal_wrap": false,
"type": "userpass" <-- ... and this one
},
"request_id": "f2a4c135-f699-f29d-ca7c-3320dce0a550",
"more_keys": "more_values",
"data": {
"more_data": {
"even_more_data": "snipped"
}
},
"you_get_the": "idea"
}
很抱歉,在复制&粘贴,但这似乎是阐明我的目标的最佳方法:
对于所有以/
结尾的根密钥,我需要使用.type
的值,以便上述示例的最终结果是token userpass
.
Sorry for the inline comments messing up the data when copying & pasting, but that seems the best way to clarify my goal:
For all root keys that end with /
, I need the value of .type
, so that the final result for the above example is token userpass
.
我设法为根密钥创建了一个有效的过滤器:
I managed to create a working filter for the root keys:
host:~ user$ jq -r '. | keys[] | endswith("/")' <<< "${json_data}"
false
false
false
true
true
false
我可以使用该过滤器仅获取所需的键,但这仅是键,而不是它们下面的整个数据结构:
and I can use that filter to get only the wanted keys, but that is the keys alone and not the entire data structures underneath them:
host:~ user$ jq -r '. | keys[] | select(. | endswith("/"))' <<< "${json_data}"
token/
userpass/
我似乎无法将所有这些都放在一起...
I just can't seem to put this all together...
有人可以帮助我吗?
推荐答案
jq
解决方案:
jq
solution:
jq -r '. as $o | keys_unsorted[] | select(endswith("/")) | $o[.].type' file.json
输出:
token
userpass
这篇关于jq:根据键是否以指定的字符串结尾来过滤输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!