简体   繁体   English

将多个json文件合并为一个python

[英]merge multiple json file into one python

I am trying to merge multiple json file into one that looks like this:我正在尝试将多个 json 文件合并为一个如下所示的文件:

file1: [[a,b],[c,d],[e,f]]
file2: [[g,h],[i,f],[k,l]]
file3: [[m,n],[o,p],[q,r]]

I am using this code to merge the files:我正在使用此代码合并文件:

data = []
for f in glob.glob("*.json"):
    with open(f,) as infile:
        data.append(json.load(infile))

with open("merged_file.json",'w') as outfile:
  json.dump(data, outfile)

out:  [[[a,b],[c,d],[e,f]],[[g,h],[i,f],[k,l]],[[m,n],[o,p],[q,r]]]

But what I really need is this:但我真正需要的是:

[[a,b],[c,d],[e,f],[g,h],[i,f],[k,l],[m,n],[o,p],[q,r]]

Instead of having separated lists, I need all the pairs in one list.我不需要单独的列表,而是需要一个列表中的所有对。

Hope someone can help me, cheers!希望有人能帮助我,干杯!

If you are sure all files become list s after json.load -ing you might replace:如果您确定所有文件在json.load -ing 之后都变成list ,您可以替换:

data.append(json.load(infile))

with

data.extend(json.load(infile))

Which should produce desired result.这应该产生预期的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM