Ansible: Merge dictionaries within a list adding values to a list

Viewed 31

How can I merge dictionaries within the list with the some properties that are the same and have the values of the properties that are different added to a list value of merged dictionary?

[
      {
        "name": "samename",
        "content": "content1"
      },
      {
        "name": "samename",
        "content": "content2"
      },
      {
        "name": "differentname",
        "content": "content3"
      }
    ]

Desired output:

[
      {
        "name": "samename",
        "content": ["content1", "content2"]
      },
      {
        "name": "differentname",
        "content": "content3"
      }
    ]
1 Answers
Given the data
data:
  - content: content1
    name: samename
  - content: content2
    name: samename
  - content: content3
    name: differentname

Use the filter json_query to create lists from the attribute content. Then use the filter community.general.lists_mergeby to merge the items, e.g.

data_groups_query: '[].{name: name, content: [content]}'
data_groups: "{{ [data|json_query(data_groups_query), []]|
                 community.general.lists_mergeby('name', list_merge='append') }}"

gives what you want

data_groups:
  - content: [content3]
    name: differentname
  - content: [content1, content2]
    name: samename
Related