json 合并2嵌套字典

lsmd5eda  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(92)

我正在尝试添加一个额外的条目到一个嵌套的字典。我能够提取嵌套的字典,追加到字典,但不能完全弄清楚如何用新创建的一个替换嵌套的部分。我有一种感觉,有一个更容易的方法来做到这一点。我只会问我想要什么,而不是张贴我已经尝试,看看它去哪里。
我需要在my_team下添加一个额外的条目,它将以var的形式出现:

ok: [localhost] => changed=false 
  json:
    OTHER_KEYS_1: value1
    OTHER_KEYS_2:
      value1
      key1: value1
    OTHER_KEYS_3:
      key1: value1
      key2: value2
      my_team:
      - org: Default
        team: TEAM-ONE-ADMINS
      - org: Default
        team: TEAM-ONE-USERS
      - org: Default
        team: TEAM-TWO-USERS
      - org: Default
        team: TEAM-TWO-ADMINS
      - org: Default
        team: TEAM-THREE-USERS
      - org: Default
        team: TEAM-THREE-ADMINS
    OTHER_KEYS_4: {}
    OTHER_KEYS_5:
      emailAddress: [email protected]
      givenName: User Name
    OTHER_KEYS_6:
      key1: value1
  msg: OK (7003 bytes)
  pragma: no-cache
  redirected: false
  server: nginx
  status: 200
  strict_transport_security: max-age=63072000
  url: https://tower/api/v2/settings/saml/?format=json
  vary: Accept, Accept-Language, Origin, Cookie

字符串

szqfcxe2

szqfcxe21#

问:“在my_team下添加其他条目。"
A:给定简化数据

data:
      k1: v1
      k2: v2
      k3:
        key1: value1
        key2: value2
        my_team:
          - {org: default, team: team_one}
          - {org: default, team: team_two}

字符串
声明您要添加的内容

data_add:
      k3:
        my_team:
          - {org: default, team: team_three}


并合并词典

result: "{{ [data, data_add]|combine(recursive=True, list_merge='append') }}"


my_team 下为字典提供一个附加条目

result:
    k1: v1
    k2: v2
    k3:
      key1: value1
      key2: value2
      my_team:
      - {org: default, team: team_one}
      - {org: default, team: team_two}
      - {org: default, team: team_three}


完整的测试行动手册示例

- hosts: all

  vars:

    data:
      k1: v1
      k2: v2
      k3:
        key1: value1
        key2: value2
        my_team:
          - {org: default, team: team_one}
          - {org: default, team: team_two}

    data_add:
      k3:
        my_team:
          - {org: default, team: team_three}

    result: "{{ [data, data_add]|combine(recursive=True, list_merge='append') }}"

  tasks:

    - debug:
        var: data|to_yaml

    - debug:
        var: result|to_yaml

相关问题