问题描述
我正在尝试根据子属性的值过滤 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 查询来过滤 属性的对象.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 playbook 的一部分,所以肯定会有一种方法来以不同的方式(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 中这是不可能的.
在 to_entries 等不同工具中有用于此目的的自定义内置函数="noreferrer">jq.
对于 jmespath.py
和 Ansible,有挂起 pull request 实现按键操作.
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 中的键选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!