英文:
Does JMESPath have an 'in' like operator, that will be true if a key's value is present in an array of strings?
问题
JMESPath有一个类似于'in'的操作符吗?如果一个键的值在一个字符串数组中存在,它会返回true吗?
给定以下数据片段(假设项目数量更多,我想选择其中几个):
[
{
"object": {
"metadata": {
"name": "item1"
}
},
"data": {}
},
{
"object": {
"metadata": {
"name": "item2"
}
},
"data": {}
},
{
"object": {
"metadata": {
"name": "item3"
}
},
"data": {}
}
]
是否有一种方法可以选择任何对象,其metadata.name键的值在列表['item1', 'item2']中?
英文:
Does JMESPath have an 'in' like operator, that will be true if a key's value is present in an array of strings?
Given the following snippet of data, (assume the number of items is much larger, and I want to select a few)
[
{
"object": {
"metadata": {
"name": "item1"
}
},
"data": {}
},
{
"object": {
"metadata": {
"name": "item2"
}
},
"data": {}
},
{
"object": {
"metadata": {
"name": "item3"
}
},
"data": {}
}
]
Is there something that would allow me to select any object, whose metadata.name key's value is in the list ['item1', 'item2']?
答案1
得分: 3
Q: "选择任何对象,其metadata.name键的值在列表['item1','item2']中"
A: 使用JmesPath内置函数contains。下面的查询可以实现你想要的功能:
[?contains(['item1', 'item2'], object.metadata.name)]
- 完整测试的示例playbook
- hosts: localhost
vars:
data:
- data: {}
object:
metadata:
name: item1
- data: {}
object:
metadata:
name: item2
- data: {}
object:
metadata:
name: item3
result: "{{ data|json_query(result_query) }}"
result_query: |
[?contains(['item1', 'item2'], object.metadata.name)]
tasks:
- debug:
var: result
输出结果(缩写)
result:
- data: {}
object:
metadata:
name: item1
- data: {}
object:
metadata:
name: item2
- 你可以将列表放入一个变量中。例如,
result: "{{ data|json_query(result_query) }}"
filter: ['item1', 'item2']
result_query: |
[?contains({{ filter }}, object.metadata.name)]
英文:
Q: "Select any object, whose metadata.name key's value is in the list ['item1', 'item2']"
A: Use the JmesPath built-in function contains. The below query does what you want
[?contains(['item1', 'item2'], object.metadata.name)]
<hr>
<sup>
- Example of a complete playbook for testing
- hosts: localhost
vars:
data:
- data: {}
object:
metadata:
name: item1
- data: {}
object:
metadata:
name: item2
- data: {}
object:
metadata:
name: item3
result: "{{ data|json_query(result_query) }}"
result_query: |
[?contains(['item1', 'item2'], object.metadata.name)]
tasks:
- debug:
var: result
gives (abridged)
result:
- data: {}
object:
metadata:
name: item1
- data: {}
object:
metadata:
name: item2
- You can put the list into a variable. For example,
result: "{{ data|json_query(result_query) }}"
filter: ['item1', 'item2']
result_query: |
[?contains({{ filter }}, object.metadata.name)]
</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论