Variable mule_runtimes有一个字典列表:
- id: N-Newton
version: 4.3.0
- id: N-Galileo
version: 3.9.0-hf4
- id: N-Einstein
version: 3.8.5-hf4我想要一本id = N-Einstein的字典。
我试过使用这个:
- debug:
msg: "{{ mule_runtimes | selectattr('id', 'equalto', 'N-Einstein') | to_json }}"和got错误:在({{ JSON | selectattr('id','equalto',‘N- to_json’)|JSON}})上出现意外的模板类型错误:'generator‘类型的对象不是JSON可序列化的。从列表中挑选字典的正确方法是什么?
发布于 2020-06-11 06:28:14
第一个问题是mule_runtimes | selectattr('id', 'equalto', 'N-Einstein')返回一个生成器。把它想象成Python语言中的d for d in mule_runtimes if d['id'] == 'N-Einstein'。在使用to_json过滤器之前,您需要将其转换为可序列化的JSON (如列表)。
第二个问题是,它没有从列表中只选择一个字典。对于多个字典,谓词id == 'N-Einstein'可能为真。如果您知道它将只匹配一个字典,则需要将该列表转换为单个字典。
把所有这些放在一起:
{{ mule_runtimes | selectattr('id', 'equalto', 'N-Einstein') | list | last | to_json }}发布于 2020-06-11 06:49:56
我建议使用json_query:
- name: dictionaries
vars:
mule_runtimes:
- id: N-Newton
version: 4.3.0
- id: N-Galileo
version: 3.9.0-hf4
- id: N-Einstein
version: 3.8.5-hf4
json: "{{ mule_runtimes }}"
query: "[?id=='{{ want }}'].version"
want: N-Einstein
debug:
msg: "{{ json | json_query(query) }}"给出输出:
TASK [test : dictionaries] *****************************************************
ok: [127.0.0.1] => {
"msg": [
"3.8.5-hf4"
]
} https://stackoverflow.com/questions/62313989
复制相似问题