如何合并多个json文件并维护模式?

2024-09-28 22:22:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有多个json文件(Benoni_0-100.json等),如下所示:

{
   "matches":[
      {
         "platformId":"TR1",
         "gameId":379560441,
         "champion":62,
         "queue":410,
         "season":7,
         "timestamp":1460529442141,
         "role":"NONE",
         "lane":"JUNGLE"
      }
   ],
   "startIndex":4200,
   "endIndex":4201,
   "totalGames":4201
}

当我尝试用下面的代码合并到两个文件时,它是有效的。你知道吗

import json

with open("Benoni_0-100.json") as fo:
    data1 = json.load(fo)

with open("Benoni_100-200.json") as fo:
    data2 = json.load(fo)

data1['matches'].extend(data2['matches'])

with open("test.json", "w") as fo:
    json.dump(data1, fo)

但是,我有多个文件,并希望批量合并。当我用下面的代码尝试它时,它失败了。你知道吗

data = '{"matches": []}'
folder = glob.glob("*.json")
for filename in folder:
    with open(filename) as file:
        data1 = json.loads(data)
        datanew = json.load(file)
        data1['matches'].extend(datanew['matches'])
with open("test.json", "w") as fo:
    json.dump(data1, fo)

输出为:

TypeError: string indices must be integers

我试了几个小时的各种方法都失败了。有人能帮我吗?你知道吗

编辑:用下面的代码解决它。你知道吗

data = '{"matches": []}'
data_1 = json.loads(data)
folder = glob.glob("*.json")

for filename in folder:
    try:
        with open(filename) as fo:
            data_new = json.load(fo)
            data_1['matches'].extend(data_new['matches'])
    except:
        print(filename)

with open("test.json", "w") as fo:
    json.dump(data_1, fo)

Tags: 文件代码jsondataaswithloadopen
2条回答

运行批合并代码时,我没有得到任何错误,输出存储在test.json。您确定代码中没有执行导致此错误的其他操作吗?你知道吗

但是,有一点需要注意,在生成的test.json中只会得到一个条目输出,因为在循环的每个迭代中都重新定义了data1。你知道吗

“matches”是一个列表,不妨把它联系起来

dict['matches'] += otherdict['matches']

如果你不是在扩展dicts,而是在扩展列表 你有一张单子

相关问题 更多 >