Flatten a partially nested list in Ansible

Viewed 56

having such a list:

[
  [[[6781,"1"]], "a"],
  [[[6782,"1"]], "b"],
  [[[6780,"1"]], "c"]
]

which filter / query would you use to "partially flatten" the list to:

[
  [6781,"1", "a"],
  [6782,"1", "b"],
  [6780,"1", "c"]
]

I tried this one, which is NOT working

- name: test
  hosts: localhost
  vars:
    data: '[
  [[[6781,"1"]], "a"],
  [[[6782,"1"]], "b"],
  [[[6780,"1"]], "c"]
]'
  tasks:
   - debug:
      msg: "{{ data | from_json | flatten}}"
1 Answers

You have a list composed of lists which you want to flatten. Applying the flatten filter to the entire list will not do what you want (as you found out) as it will flatten the entire list to a single level.

What you want is to apply that same filter but individually to each element of your top list. This could eventually be done by looping over your list and constructing the result iteratively using set_fact.

But the map filter does the job in one go:

  - debug:
      msg: "{{ data | from_json | map('flatten') }}"

Some usefull references:

Related