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

如何在Ansible中构建键为颜色类型、值为颜色列表的字典?

用Ansible将颜色类型转换为指定字典结构

给定如下JSON数据:

msg: [
  {
    "name": "Primary_colors",
    "sub_attrs": [
        {
            "name": "Red"
        },
        {
            "name": "Blue"
        },
        {
            "name": "Yellow"
        }
    ]
  },
  {
    "name": "Secondary_colors",
    "sub_attrs": [
        {
            "name": "Green"
        },
        {
            "name": "Orange"
        },
        {
            "name": "Purple"
        }
    ]
  }
]

需求是把每种颜色类型的名称作为字典的键,sub_attrs中的name属性组成列表作为对应键的值。当前的set_fact任务只能单独提取颜色类型和颜色名称列表,无法完成分组:

- name: Set facts
  set_fact:
    types_of_colors: '{{ msg | map(attribute="name") | list }}' 
    names_of_colors: '{{ msg | map(attribute="sub_attrs") | sum(start=[]) | map(attribute="name") | list }}'

期望得到的数据结构:

Primary_colors:
  - Red
  - Blue
  - Yellow
Secondary_colors:
  - Green
  - Orange
  - Purple

解决方案

方法1:用json_query+items2dict快速转换

这是最简洁的实现,一步到位:

- name: 生成目标颜色字典
  set_fact:
    color_dict: "{{ msg | json_query('[].{key: name, value: sub_attrs[].name}') | items2dict }}"

解释:

  • json_query('[].{key: name, value: sub_attrs[].name}'):遍历msg中的每个元素,将每个元素转换为{key: 颜色类型名, value: 颜色列表}的结构
  • items2dict:把这些键值对结构直接合并成一个完整的字典

方法2:循环遍历合并字典

如果需要更直观的分步逻辑,可以用循环逐个处理每个颜色类型:

- name: 初始化空字典
  set_fact:
    color_dict: {}

- name: 逐个生成颜色类型的键值对并合并
  set_fact:
    color_dict: "{{ color_dict | combine({ item.name: item.sub_attrs | map(attribute='name') | list }) }}"
  loop: "{{ msg }}"

解释:

  • 先初始化一个空字典color_dict
  • 循环遍历msg中的每个元素,对每个元素提取颜色类型名作为键,提取sub_attrs里的颜色名称组成列表作为值,然后用combine把这个键值对合并到color_dict中

结果验证

执行任意一种方法后,color_dict变量的结构都会和期望一致:

color_dict:
  Primary_colors:
    - Red
    - Blue
    - Yellow
  Secondary_colors:
    - Green
    - Orange
    - Purple

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 15:25:29