0

I have 3 json files as below:

test1.json:

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

test2.json:

{"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
3
  • 1
    FYI your desired result in not valid JSON. Commented Mar 8, 2022 at 15:08
  • 1
    While producing your desired output is possible, it is not JSON. Commented Mar 8, 2022 at 15:09
  • Maybe you're not looking for a JSON string, but rather an array? Commented Mar 8, 2022 at 15:12

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.