【问题标题】:Combining JSON Files Without Overriding在不覆盖的情况下组合 JSON 文件
【发布时间】:2016-03-03 18:21:48
【问题描述】:

我有 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 中做到这一点?

【问题讨论】:

    标签: python json merge


    【解决方案1】:

    你想使用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]]
    

    这就是在您的尝试中创建“不必要的方括号”的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-06
      相关资源
      最近更新 更多