json 使用ansible合并字典列表

nue99wik  于 2023-02-20  发布在  其他
关注(0)|答案(1)|浏览(181)

我正试图合并两个字典列表。

"my_name": 
[ {
"name": "xyz",
"number": "123" },
{
"name": "abc",
"number": "456"
}
]

"my_address":
[ {
"name": "abc",
"address": "smith street" },
{
"name": "xyz",
"number": "ray street"
}
]

要求输出:
合并:

[ {
"name": "abc",
"address": "smith street",
"number": "456" },
{
"name": "xyz",
"address": "ray street",
"number": "123"
}
]

我尝试使用combine,但它只会合并最后一项。

set_fact:
  merged: "{{ my_name | combine(my_address) }}"

"merged":
[
{
"name": "xyz",
"number": "ray street",
"number": "123"
}
]

我使用了调试模块。调试:消息:“{{我的姓名|list_mergeby(我的地址,'name')}}”错误是:模板字符串时发生模板错误:没有名为“lists_mergby”的过滤器,

wfsdck30

wfsdck301#

例如,给定固定的 my_address

- hosts: localhost

  vars:

    my_name:
      - name: xyz
        number: '123'
      - name: abc
        number: '456'

    my_address:
      - name: abc
        address: smith street
      - name: xyz
        address: ray street

    merged: "{{ [my_name, my_address]|community.general.lists_mergeby('name') }}"

  tasks:

    - debug:
        var: merged

给出(删节)

merged:
  - address: smith street
    name: abc
    number: '456'
  - address: ray street
    name: xyz
    number: '123'

参见:过滤器community.general.lists_mergeby

相关问题