Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am trying to merge the multiple json file into one which looks like this:

file1: [[a,b],[c,d],[e,f]]

file2: [[g,h],[i,f],[k,l]]

file3: [[m,n],[o,p],[q,r]]

I am using the below 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 want is:

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

Instead of having separated lists, I wanted them in one list.

1 Answer

0 votes
by (36.8k points)

If you are sure all the files become lists after json.load-ing you should replace:

data.append(json.load(infile))

with

data.extend(json.load(infile))

If you are a beginner and want to know more about Python the do check out the python for data science course

If you are interested to learn Python from Industry experts, you can sign up for this Python Certification Course by Intellipaat.

Browse Categories

...