You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过单任务/Jinja2从字典列表提取并映射多嵌套属性?

如何用Ansible单任务/Jinja2过滤器提取列表对象的指定属性并生成新列表

完全可以通过单任务结合Jinja2过滤器或Ansible内置功能实现,以下是两种核心场景的具体实现:

场景1:保留原属性名提取

如果只需要提取msg和invocation.module_args.path并保留原属性名(msg、path),可以使用json_query过滤器(基于JMESPath语法),在单个set_fact任务中完成:

- name: 提取指定属性生成新列表
  ansible.builtin.set_fact:
    new_list: "{{ original_list | json_query('[].{msg: msg, path: invocation.module_args.path}') }}"

效果验证

执行后new_list的内容将完全匹配你期望的结果:

[
  {
    "msg": "Error while parsing document: files/file1.xml (Opening and ending tag mismatch)",
    "path": "files/file1.xml"
  },
  {
    "msg": "Error while parsing document: files/file2.xml (Opening and ending tag mismatch)",
    "path": "files/file2.xml"
  }
]

场景2:自定义新属性名

如果需要将属性名自定义为error(对应原msg)和file(对应原invocation.module_args.path),有两种简洁实现方式:

方式1:用json_query直接指定新键名

只需修改JMESPath表达式中的键名即可:

- name: 提取属性并自定义键名
  ansible.builtin.set_fact:
    custom_new_list: "{{ original_list | json_query('[].{error: msg, file: invocation.module_args.path}') }}"

方式2:用Jinja2列表推导式

如果对JMESPath不熟悉,直接用Jinja2的列表推导式更直观:

- name: 用Jinja2推导式构造自定义属性列表
  ansible.builtin.set_fact:
    custom_new_list: "{{ [ {'error': item.msg, 'file': item.invocation.module_args.path} for item in original_list ] }}"

效果验证

两种方式生成的custom_new_list都会符合你的自定义需求:

[
  {
    "error": "Error while parsing document: files/file1.xml (Opening and ending tag mismatch)",
    "file": "files/file1.xml"
  },
  {
    "error": "Error while parsing document: files/file2.xml (Opening and ending tag mismatch)",
    "file": "files/file2.xml"
  }
]

说明

以上所有实现都无需额外的循环任务,仅通过单个set_fact任务即可完成属性提取与转换,完全满足简化需求。

内容的提问来源于stack exchange,提问作者jeremywat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 16:26:08