组合JSON文件而不覆盖

时间:2016-03-03 18:21:48

标签: python json merge

我有2个JSON文件,它们的键名相同。如何在不重写Python的情况下组合这些文件?我尝试了这两种方法:

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

如何在Python中完成?

1 个答案:

答案 0 :(得分:2)

您想要使用list.extend()方法,如下所示:

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

l1.extend(l2)方法会通过附加l1中的项目来扩展l2,如下所示:

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

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