英文:
Merge List of Dictionary using ansible
问题
I am trying to merge two list of dictionaries.
"my_name":
[ {
"name": "xyz",
"number": "123" },
{
"name": "abc",
"number": "456"
}
]
"my_address":
[ {
"name": "abc",
"address": "smith street" },
{
"name": "xyz",
"number": "ray street"
}
]
Required Output:
merged:
[ {
"name": "abc",
"address": "smith street",
"number": "456" },
{
"name": "xyz",
"address": "ray street",
"number": "123"
}
]
I tried using combine
but it would just combine the last item.
set_fact:
merged: "{{ my_name | combine(my_address) }}"
"merged":
[
{
"name": "xyz",
"number": "ray street",
"number": "123"
}
]
I used the debug module. debug: msg: "{{ my_name| list_mergeby(my_address,'name')}}" The error was: template error while templating string: no filter named 'lists_mergby,
英文:
I am trying to merge two list of dictionaries.
"my_name":
[ {
"name": "xyz",
"number": "123" },
{
"name": "abc",
"number": "456"
}
]
"my_address":
[ {
"name": "abc",
"address": "smith street" },
{
"name": "xyz",
"number": "ray street"
}
]
Required Output:
merged:
[ {
"name": "abc",
"address": "smith street",
"number": "456" },
{
"name": "xyz",
"address": "ray street",
"number": "123"
}
]
I tried using combine
but it would just combine the last item.
set_fact:
merged: "{{ my_name | combine(my_address) }}"
"merged":
[
{
"name": "xyz",
"number": "ray street",
"number": "123"
}
]
i used the debug module. debug: msg: "{{ my_name| list_mergeby(my_address,'name')}}" The error was: template error while templating string: no filter named 'lists_mergby,
答案1
得分: 1
例如,给定固定的 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
英文:
For example, given the fixed 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
gives (abridged)
merged:
- address: smith street
name: abc
number: '456'
- address: ray street
name: xyz
number: '123'
See: the filter community.general.lists_mergeby
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论