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
是动态的,下次会改变,我不知道确切的值,这就是为什么我需要使用通配符。我需要获取版本为 4
.
的键 addr
的值
我期待输出 89 Psr
我使用函数 startswith()
尝试了以下操作。
jq '.detail.addresses | select(startswith("ext"))'
但它以错误结束。
jq: error (at :0): startswith() requires string inputs
如果您不关心正在搜索的对象中的键,您可以使用 []
搜索对象的值,然后您可以过滤到您想要的结果。
.details.addresses[][] | select(.version == 4).addr
另一方面,如果您想 select 具有版本 4 的密钥,您可以使用 to_entries
来执行此操作:
.details.addresses | to_entries[] | select(any(.value[]; .version == 4)).key
如果按照部分问题的建议,您希望将搜索限制为以 "ext":
开头的键名
.details.addresses
| to_entries[]
| select(.key|startswith("ext"))
| .value[]
| select(.version == 4)
| .addr
走向宽容的另一端:
.details.addresses
| ..
| objects
| select(.version==4)
| .addr
我有以下 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
是动态的,下次会改变,我不知道确切的值,这就是为什么我需要使用通配符。我需要获取版本为 4
.
addr
的值
我期待输出 89 Psr
我使用函数 startswith()
尝试了以下操作。
jq '.detail.addresses | select(startswith("ext"))'
但它以错误结束。
jq: error (at :0): startswith() requires string inputs
如果您不关心正在搜索的对象中的键,您可以使用 []
搜索对象的值,然后您可以过滤到您想要的结果。
.details.addresses[][] | select(.version == 4).addr
另一方面,如果您想 select 具有版本 4 的密钥,您可以使用 to_entries
来执行此操作:
.details.addresses | to_entries[] | select(any(.value[]; .version == 4)).key
如果按照部分问题的建议,您希望将搜索限制为以 "ext":
开头的键名.details.addresses
| to_entries[]
| select(.key|startswith("ext"))
| .value[]
| select(.version == 4)
| .addr
走向宽容的另一端:
.details.addresses
| ..
| objects
| select(.version==4)
| .addr