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

如何用Ansible的Jinja模板rejectattr删除嵌套字典中的peach

解决方法

要保留原始嵌套字典结构并移除peach,你需要重构整个嵌套字典,而不是只提取处理后的fruit字段。可以结合combine过滤器和循环来实现:

tasks:
  - set_fact:
      test: >-
        {% set processed = {} %}
        {% for season, months in fruits.items() %}
          {% set season_dict = { season: {} } %}
          {% for month, details in months.items() %}
            {% set filtered_fruit = details.fruit | dict2items | rejectattr('key', 'eq', 'peach') | items2dict %}
            {% set month_details = details | combine({'fruit': filtered_fruit}) %}
            {% set season_dict = season_dict | combine({ season: season_dict[season] | combine({ month: month_details }) }) %}
          {% endfor %}
          {% set processed = processed | combine(season_dict) %}
        {% endfor %}
        {{ processed }}

结果说明

执行后test变量会保留原始的嵌套结构,仅移除july下的peach:

{
  "summer": {
    "june": {
      "fruit": {
        "cherry": "cherry"
      },
      "vars": {}
    },
    "july": {
      "fruit": {},
      "vars": {}
    },
    "august": {
      "fruit": {
        "watermelon": "watermelon",
        "strawberry": "strawberry"
      },
      "vars": {}
    }
  }
}

关键思路

  • 逐层遍历原始字典的层级(季节→月份→详情)
  • 对每个月份的fruit字段用rejectattr过滤掉peach
  • 用combine过滤器将处理后的fruit字段合并回原月份详情,再逐层合并回季节、顶层字典,从而保留完整结构

如果想要直接移除july这个月份(而不是只清空它的fruit),可以在遍历月份时加判断:

tasks:
  - set_fact:
      test: >-
        {% set processed = {} %}
        {% for season, months in fruits.items() %}
          {% set season_dict = { season: {} } %}
          {% for month, details in months.items() %}
            {% if month != 'july' %}
              {% set season_dict = season_dict | combine({ season: season_dict[season] | combine({ month: details }) }) %}
            {% endif %}
          {% endfor %}
          {% set processed = processed | combine(season_dict) %}
        {% endfor %}
        {{ processed }}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 22:40:56