Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join or unionize a list of list elements (unknown length)

Tags:

json

ansible

I'm parsing some values using json_query. After extracting the values I'm left with a list of elements which contain the list of values. My goal is to have a single list of un-nested values.
How can I achieve this?

E.g.:

my_list: [ [1,2],[3,4],[5,6] ]

Should become

my_list: [1,2,3,4,5,6]

I can't use my_list[0] | union([my_list[1]) | union(my_list[2]) because the my_list is dynamic.

like image 505
Mint Avatar asked Jan 27 '26 09:01

Mint


1 Answers

Use the flatten filter.

Given:

- debug:
    msg: "{{ [ [1,2],[3,4],[5,6] ] | flatten(1) }}"

This yields the expected list:

ok: [localhost] => 
  msg:
  - 1
  - 2
  - 3
  - 4
  - 5
  - 6

And since you state that you are using json_query, note that there is also a way to flatten in JMESPath, called flatten projection, so you might bake this is your existing query.

As an example:

- debug:
    msg: "{{ [ [1,2],[3,4],[5,6] ] | json_query('[]') }}"

Will also yield the expected result.

like image 100
β.εηοιτ.βε Avatar answered Jan 30 '26 09:01

β.εηοιτ.βε



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!