Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combining json files in python

I have 3 json files as below:

test1.json:

{"item":"book1","price":"10.00","location":"library"}

test2.json:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{"item":"book2","price":"15.00","location":"store"}

test3.json:

{"item":"book3","price":"9.50","location":"store"}

I have this code:

import json
import glob

result = ''
for f in glob.glob("*.json"):
    with open (f, "r") as infile:
        result += infile.read()

with open("m1.json", "w") as outfile:
    outfile.writelines(result)

I get the following output:

{"item":"book1","price":"10.00","location":"library"} 
{"item":"book2","price":"15.00","location":"store"}
{"item":"book3","price":"9.50","location":"store"}

Is it possible to get each file as a new line separated by a comma like below?

{"item":"book1","price":"10.00","location":"library"},  <-- line 1
{"item":"book2","price":"15.00","location":"store"},    <-- line 2
{"item":"book3","price":"9.50","location":"store"}      <-- line 3

>Solution :

As others commented, your expected result is invalid json.
But if you really want the format, use str.join() is more convenient.

jsons = []
for f in glob.glob("*.json"):
    with open (f, "r") as infile:
        jsons.append(infile.read())
result = ',\n'.join(jsons)

infile.read() gets the string, d = json.loads(infile.read()) can get a real json object(dict).

To write a valid combined json(of type list(of dict)), just write s = json.dumps(jsons) to file.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading