如何使用jq通配符 [英] How to use jq wildcard
问题描述
我有以下json:
{
"details":{
"car": "bmw",
"addresses":{
"ext-118-21-8-0-29":[
{
"version":4,
"addr":"89 Psr"
},
{
"version":6,
"addr":"56 apT"
}
]
}
}
}
键 ext-118-21-8-0-29
是动态的,下次它将更改,我不知道确切的值,这就是为什么我需要使用通配符.我需要获取键 addr
的值,其中版本为 4
.
The key ext-118-21-8-0-29
is dynamic it will change the next time and I don't know the exact value, that's why I need to use wildcard. I need to get the value of the key addr
where version is 4
.
我期望输出为 89 Psr
我使用功能 startswith()
尝试了以下操作.
I tried the following using the function startswith()
.
jq '.detail.addresses | select(startswith("ext"))'
但是它以错误结尾.
jq:错误(在:0处):startswith()需要字符串输入
jq: error (at :0): startswith() requires string inputs
推荐答案
如果您不关心要搜索的对象中的键,则可以使用 []
,然后可以过滤到所需的结果.
If you don't care about the keys in the object you're searching, you could just search the values of the object using []
which you could then filter to your desired results.
.details.addresses[][] | select(.version == 4).addr
另一方面,如果您想选择具有版本4的键,则可以使用 to_entries
进行此操作:
If on the other hand you wanted to select keys that has a version 4, you could use to_entries
to do this:
.details.addresses | to_entries[] | select(any(.value[]; .version == 4)).key
这篇关于如何使用jq通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!