3

I have a lot of JSON files like the following:

E.g.

1.json

{"name": "one", "description": "testDescription...", "comment": ""}

test.json

{"name": "test", "description": "testDescription...", "comment": ""}

two.json

{"name": "two", "description": "testDescription...", "comment": ""}

...

I want to merge them all in one JSON file like:

merge_json.json

{"name": "one", "description": "testDescription...", "comment": ""},
{"name": "test", "description": "testDescription...", "comment": ""},
{"name": "two", "description": "testDescription...", "comment": ""}

I have the following code:

import json
import glob

result = []
for f in glob.glob("*.json"):
    with open(f, "r") as infile:
        try:
            result.append(json.load(infile))
        except ValueError as e:
            print(f,e)
result = '\n'.join(result)

with open("merged.json", "w", encoding="utf8") as outfile:
    json.dump(result, outfile)

I can merge all files, but everything are in a one line how can I add break-line, after adding each file:

instead of:

{"name": "one", "description": "testDescription...", "comment": ""},{"name": "test", "description": "testDescription...", "comment": ""},{"name": "two", "description": "testDescription...", "comment": ""}

Have them like:

merge_json.json

{"name": "one", "description": "testDescription...", "comment": ""},
{"name": "test", "description": "testDescription...", "comment": ""},
{"name": "two", "description": "testDescription...", "comment": ""}

Appreciated for any help.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Jan Tamm
  • 117
  • 2
  • 11
  • probably pretty printing should do it: https://docs.python.org/2/library/json.html you will have to figure out the exact combination of parameters on your own – E.Serra Oct 12 '18 at 16:11
  • Possible duplicate of [Python JSON dump / append to .txt with each variable on new line](https://stackoverflow.com/questions/17055117/python-json-dump-append-to-txt-with-each-variable-on-new-line) – mad_ Oct 12 '18 at 16:11
  • outfile.write(result) – whymatter Oct 12 '18 at 16:17
  • infile.read() might also be enough to get the job done without parsing the json just to write is back to a file – whymatter Oct 12 '18 at 16:22

1 Answers1

1
result = []
for f in glob.glob("*.json"):
    with open(f, "r") as infile:
        try:
            result.append(json.load(infile))
        except ValueError as e:
            print(f,e)

with open("merged.json", "a", encoding="utf8") as outfile:
    for i in result:
        json.dump(i, outfile)
        outfile.write('\n')
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20