【发布时间】: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 中做到这一点?
【问题讨论】: