How to combine 2 list based on a common key value in Ansible Jinja2
I am trying to combine a particular value into a list based on a common key(organizationId) value from a JSON array. Here i am using a Jinja template to create a Json file that will be used for further processing. So here sample.json is the JSON file from where the test.j2(Jinja template) will be fetching the values to make a final JSON(mentioned below as Expected output)
Sample.json
[
{
"id": "111222333444627213",
"organizationId": "111222333444624074"
},
{
"id": "111222333444627214",
"organizationId": "111222333444624074"
},
{
"id": "111222333444627216",
"organizationId": "111222333444624074"
},
{
"id": "111222333444627217",
"organizationId": "12345678"
}
]
test.j2(Jinja)
[
{% for dict_item in sample.json %}
{
"orgid":"{{dict_item['organizationId']}}",
"objectIds":[
"{{ dict_item['id']}}"
]
}{% if not loop.last %},
{% endif %}
{% endfor %}
]
Expected Output
[
{
"orgid":"111222333444624074",
"objectIds":[
"111222333444627213",
"111222333444627214",
"111222333444627216",
]
},
{
"orgid":"12345678",
"objectIds":[
"111222333444627217"
]
}
]
Jinja2 is not needed. Instead, iterate the list created by the filter groupby. For example
- set_fact:
output: "{{ output|d([]) + [{'orgid': item.0,
'objectIds': item.1|
map(attribute='id')|
list}] }}"
loop: "{{ sample.json|groupby('organizationId') }}"
gives
output:
- objectIds:
- '111222333444627213'
- '111222333444627214'
- '111222333444627216'
orgid: '111222333444624074'
- objectIds:
- '111222333444627217'
orgid: '12345678'