首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不可修改嵌套字典中的删除值

不可修改嵌套字典中的删除值
EN

Stack Overflow用户
提问于 2022-05-13 22:42:45
回答 1查看 35关注 0票数 0

我想在嵌套字典中添加新值,并删除旧值。

这是我的parse.json文件。

代码语言:javascript
复制
{
    "class": "Service_HTTPS",
    "layer4": "tcp",
    "profileTCP": {
        "egress": {
            "use": "/Common/Shared/f5-tcp-wan"
        },
        "ingress": {
            "use": "/Common/Shared/f5-tcp-lan"
        }
    }
}

这是我的脚本,它将增加新的值,但也是保留旧的值,我知道我使用的是recursive=True,但是没有这个命令,我就丢失了入口键。

这是我的剧本:

代码语言:javascript
复制
- set_fact:
        json_file: "{{ lookup('file', 'parse.json')   }}"
    

    - set_fact:
        json_file: "{{ json_file | combine( egress_modify, recursive=True) }}"
      when: json_file['profileTCP']['egress'] is defined
      vars: 
        egress_modify: "{{ json_file  | combine({ 'profileTCP': { 'egress': { 'bigip': '/Common/' + json_file['profileTCP']['egress']['use'].split('/')[-1] } }}) }}" 
        

    - name: debug
      debug:
          msg: "{{ json_file }}"

错误结果

代码语言:javascript
复制
ok: [localhost] => {
    "msg": {
        "class": "Service_HTTPS",
        "layer4": "tcp",
        "profileTCP": {
            "egress": {
                "bigip": "/Common/f5-tcp-wan",
                "use": "/Common/Shared/f5-tcp-wan"
            },
            "ingress": {
                "use": "/Common/Shared/f5-tcp-lan"
            }
        }
    }
}

但我想得到这个结果

代码语言:javascript
复制
ok: [localhost] => {
    "msg": {
        "class": "Service_HTTPS",
        "layer4": "tcp",
        "profileTCP": {
            "egress": {
                "bigip": "/Common/f5-tcp-wan",
            },
            "ingress": {
                "use": "/Common/Shared/f5-tcp-lan"
            }
        }
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-14 03:20:40

dict是ansible中的"live“,所以您可以继续执行"set_fact:,循环:”业务,也可以一次性完成所有操作:

代码语言:javascript
复制
    - set_fact:
        json_file: >-
          {%- set j = lookup('file', 'parse.json') | from_json -%}
          {%- set tcp_egress_use = j.profileTCP.egress.pop('use') -%}
          {%- set _ = j.profileTCP.egress.update({
                'bigip': '/Common/' + tcp_egress_use.split('/')[-1]
              }) -%}
          {{ j }}

产生

代码语言:javascript
复制
    "json_file": {
      "class": "Service_HTTPS",
      "layer4": "tcp",
      "profileTCP": {
        "egress": {
          "bigip": "/Common/f5-tcp-wan"
        },
        "ingress": {
          "use": "/Common/Shared/f5-tcp-lan"
        }
      }
    }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72236031

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档