'how to Combine N JSONs of a loop through unique and common keys?

I would like to know what it would be like to combine N json from a list going through them and resulting in their unification through unique keys in python. For example:

I have this:

json1 = {'status': ok , places : [{name:'Mexico' ,availability:
'yes','code': 'MEX'}, {name:'Chile' ,availability: 'yes','code':
'CHL'}] }

json2 = {'status': ok , places : [{name:'Peru' ,availability:
 'yes','code': 'PE'},{name:'Argentina' ,availability: 'yes','code':
 'ARG'}] }

json3 = {'status': ok , places : [{name:'Colombia' ,availability: 'yes','code': 'CO'}]}

list_json = [json1, json2, json3] #could be more

I was thinking for i in list_json

but i would like to get something like this:

json_result = {'status': ok , places : [{name:'Mexico' ,availability:
'yes','code': 'MEX'}, {name:'Chile' ,availability: 'yes','code':
'CHL'}, {name:'Peru' ,availability: 'yes','code': 'PE'},{name:'Argentina' ,availability: 'yes','code': 'ARG'}, {name:'Colombia' ,availability: 'yes','code': 'CO'}] }


Solution 1:[1]

This can be solved using a double list comprehension.

First, let me modify your data so I can just paste it into my python interpreter:

json1 = {'status': 'ok' , 'places' : [
    {'name':'Mexico', 'availability':'yes','code': 'MEX'},
    {'name':'Chile', 'availability': 'yes','code': 'CHL'}
] }

json2 = {'status': 'ok' , 'places' : [
    {'name':'Peru', 'availability': 'yes','code': 'PE'},
    {'name':'Argentina', 'availability': 'yes','code': 'ARG'}
] }

json3 = {'status': 'ok' , 'places' : [
    {'name':'Colombia', 'availability': 'yes', 'code': 'CO'}
] }

list_json = [json1, json2, json3]

Now, this comprehension produces the output you ask for:

json_results = {'status': 'ok', 'places': [
    place
    for record in list_json
    for place in record['places']
]}

If you're not familiar with list comprehensions in Python, that code is equivalent to the following nested loop:

json_results = {'status': 'ok', 'places': []}
for record in list_json:
    for place in record['places']:
        json_results['places'].append(place)

Now, you did not specify how you wanted the status merged, so I just hard-coded it. You might have to adjust the logic if some of your records have different statuses and if that should change the output.

In any case, the idea is simply to dive into your structures and extract the information you're looking for at the right place.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1