2016-03-03 172 views
1

我有2個JSON文件的鍵名相同。如何在不覆蓋Python的情況下合併這些文件?我已經試過這兩種方法:不覆蓋JSON文件

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

^這會覆蓋在json_one數據。

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

^這幾乎是正確的,但增加了不必要的方括號。

這裏是我的2個文件: 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 
    } 
] 

文件我要創建的是:

"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 
    } 
] 

怎麼可以這樣在做蟒蛇?

回答

2

您要使用的list.extend()方法如下:

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

l1.extend(l2)方法將通過附加的項目從l2延長l1如下:

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

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

In [16]: l1.extend(l2) 

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

l1.append(l2)方法只會追加對象l2改爲:

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]] 

這是在你的嘗試中創建'不必要的方括號'。