按属性过滤对象并在jmespath中使用键进行选择 [英] Filter object by property and select with key in jmespath
问题描述
我正在尝试根据子属性的值过滤 jmespath 中的对象属性,并希望包含仅将子属性设置为特定值的那些属性.
I'm trying to filter properties of an object in jmespath based on the value of a subproperty and want to include only those properties where the subproperty is set to a specific value.
基于此示例数据:
{
"a": {
"feature": {
"enabled": true,
}
},
"b": {
},
"c": {
"feature": {
"enabled": false
}
}
}
我想获取一个具有启用该功能的所有属性的对象.
I'd like to get an object with all properties where the feature is enabled.
{
"a": {
"feature": {
"enabled": true,
}
}
}
我认为我可以使用此jmespath查询来过滤property. enabled
设置为true的对象.不幸的是,它似乎不起作用,而是返回一个空数组.
I figured I could use this jmespath query to filter the objects where property. enabled
is set to true. Unfortunateley, it doesn't seem to work and instead returns an empty array.
*[?feature.enabled==`true`]
*.feature.enabled
或*[feature.enabled]
仅返回布尔值,而没有任何上下文.
*.feature.enabled
or *[feature.enabled]
return just the boolean values without any context.
即使*[?feature.enabled==
true ]
可以工作,它也只是属性值的数组,但是我还需要键(a
和c
).有什么办法可以使它在jmespath中发生?
Even if *[?feature.enabled==
true]
would work, it would just be an array of the property values, but I need the keys (a
and c
) aswell. Is there any way to make this happen in jmespath?
这都是ansible剧本的一部分,因此肯定会有一种以其他方式(Jinja2模板或自定义插件)实现选择的方法,但是我想尝试jmespath并会推理,它应该能够做到这一点一个任务.
This is all part of an ansible playbook, so there would certainly be a way to achieve selection in a different way (Jinja2 templates or custom plugin) but I wanted to try jmespath and would reason, that it should be capable of such a task.
推荐答案
对不起,但是AFAIK在本机JMESPath中是不可能的.
在不同工具中,例如
对于jmespath.py
以及对Ansible而言,悬挂拉请求来实现密钥操作.
Sorry, but AFAIK this is impossible in native JMESPath.
There are custom built-in functions for this purpose in different tools like to_entries
in jq.
For jmespath.py
and thus for Ansible there is hanging pull request to implement keys manipulation.
更新:我制作了 json_query 过滤器.
有关其他信息,请参见此答案.
Update: I've made a patched version of json_query filter.
See this answer for additional info.
这篇关于按属性过滤对象并在jmespath中使用键进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!