I have multiple json files clubbed together inside a single log file(huge). Some of the json have got pretty formatting, but most have not. What is the best way in python to redirect the json to another file with pretty formatting.(Each json file ends with 3 '}' with sometimes newlines and spaces in between). Eg:- { "Sports":{"cricket":{"batsman": "Bradman","bowler":"Warne"}}}
Asked
Active
Viewed 121 times
2 Answers
0
First you should load the file with json.load
, then use the indent option is json.dump
.
import json
initial = json.load('yourfile.json')
json.dump(initial, 'yourfile.json', indent = 4)
you can also use the sort_keys option, which sorts the keys for the json file.
json.dump(initial, 'yourfile.json', sort_keys = True, indent = 4)
If you have multiple valid json files in one big file, you can do this:
with open('yourfile.json') as fp:
file = fp.read()
file = "[" + file + "]"
initial = json.loads(file)
This well work as long as there's commas sparating them.

Taku
- 31,927
- 11
- 74
- 85
-
The file itself is a log file, which contains hundreds of json files, so I can't use json.load I guess. – user3049437 Mar 28 '17 at 20:14
-
Does it only contain hundreds of json files and nothing else? – Taku Mar 28 '17 at 20:15
-
Just to be sure, do you mind posting exactly a portion of the file to your question? It will be nice for the answerers to see what kind of file we're dealing with. Thanks – Taku Mar 28 '17 at 20:26
-
{ "track": { "track_data": { "trackId": "1A11", "serial": 727, "ZoneInfo": "ABF2227D", "Amount": 1490, "Area": "ari-152" }, "MiscData": { "State": "developing", "Type": "Type-1", "Issues": "N/A", "Indic": "positive" } } } – user3049437 Mar 28 '17 at 20:45
-
There are no commas seperating them, but the json files are valid,with the above code it is expecting delimiter. – user3049437 Mar 28 '17 at 20:48
-
The code you posted above is only one json, do you mean you have multiple files like that one after another without commas or anything separating them? – Taku Mar 28 '17 at 23:57
-
If the answer is still no, you could try something like this question http://stackoverflow.com/questions/8730119/retrieving-json-objects-from-a-text-file-using-python – Taku Mar 29 '17 at 00:04
-
It is not allowing me to paste more , yes I have multiple files like that one after another without any delimiter. – user3049437 Mar 30 '17 at 05:58