2016-03-03 129 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]] 

这是在你的尝试中创建'不必要的方括号'。