drake
drake

Reputation: 259

Combining JSON Files Without Overriding

I have 2 JSON files that have the same names for keys. How can I combine these files without overriding in Python? I have tried both of these methods:

z = json_one.copy()
z.update(json_two)

^This overrides the data that is in json_one.

json_one['metros'].append(json_two['metros'])

^This is almost correct, but adds unnecessary square brackets.

Here are my 2 files: json_one:

"metros" : [
    {
        "code" : "SCL" ,
        "name" : "Santiago" ,
        "country" : "CL" ,
        "continent" : "South America" ,
        "timezone" : -4 ,
        "coordinates" : {"S" : 33, "W" : 71} ,
        "population" : 6000000 ,
        "region" : 1
    } , {
        "code" : "LIM" ,
        "name" : "Lima" ,
        "country" : "PE" ,
        "continent" : "South America" ,
        "timezone" : -5 ,
        "coordinates" : {"S" : 12, "W" : 77} ,
        "population" : 9050000 ,
        "region" : 1
    } 
]

json_two:

"metros" : [
    {
       "code": "CMI",
       "name": "Champaign",  
       "country": "US", 
       "continent": "North America", 
       "timezone": -6, 
       "coordinates": {"W": 88, "N": 40},
       "population": 226000, 
       "region": 1
     }
]

The file I want created is this:

"metros" : [
    {
        "code" : "SCL" ,
        "name" : "Santiago" ,
        "country" : "CL" ,
        "continent" : "South America" ,
        "timezone" : -4 ,
        "coordinates" : {"S" : 33, "W" : 71} ,
        "population" : 6000000 ,
        "region" : 1
    } , {
        "code" : "LIM" ,
        "name" : "Lima" ,
        "country" : "PE" ,
        "continent" : "South America" ,
        "timezone" : -5 ,
        "coordinates" : {"S" : 12, "W" : 77} ,
        "population" : 9050000 ,
        "region" : 1
    } , {
        "code": "CMI",
        "name": "Champaign",  
        "country": "US", 
        "continent": "North America", 
        "timezone": -6, 
        "coordinates": {"W": 88, "N": 40},
        "population": 226000, 
        "region": 1
     }
]

How can this be done in Python?

Upvotes: 1

Views: 120

Answers (1)

gtlambert
gtlambert

Reputation: 11961

You want to use the list.extend() method as follows:

json_one['metros'].extend(json_two['metros'])

The l1.extend(l2) method will extend l1 by appending the items from l2 as follows:

In [14]: l1 = [1, 2]

In [15]: l2 = [3, 4]

In [16]: l1.extend(l2)

In [17]: l1
Out[17]: [1, 2, 3, 4]

The l1.append(l2) method will just append the object l2 instead:

In [17]: l1
Out[17]: [1, 2, 3, 4]

In [18]: l1 = [1, 2]

In [19]: l2 = [3, 4]

In [20]: l1.append(l2)

In [21]: l1
Out[21]: [1, 2, [3, 4]]

This is what created the 'unnecessary square brackets' in your attempt.

Upvotes: 2

Related Questions