- 10 months ago 45
JSON Question

indent is broken after saving back updated json dict to file

I have a nested dictionary with many items in a json file:

"Create Code For Animals": {
"mammals": {
"dog": {
"color": "brown",
"name": "John",
"legs": "four",
"tail": "yes"
"cat": {
"color": "blue",
"name": "Johnny",
"legs": "four",
"tail": "yes"
"donkey": {
"color": "grey",
"name": "Mickey",
"legs": "four",
"tail": "yes"

I want to replace the name in each one of the animals, then save it back to the file, AND keep the indent as it was (as shown).
I'm using the following 2 methods for loading and dumping the original and updated dictionary.

All is working well (for changing the value and saving it back to the file) except the indent (format) of the lines is ruined after saving the file and the file is saved as one long line (with '\n' shown after the updated value).

I've tried using 'pickle' (as seen in one of the posts here), but this didn't work, made a mess of all the data in the file.

def loadJson(self, jsonFilename):
with open(FILE_PATH + '\\' + jsonFilename, 'r') as f:
return json.load(f)

def writeJson(self, jsonFilename, jsonDict):
with open(FILE_PATH + '\\' + jsonFilename, 'w') as f:
return json.dump(jsonDict, f)

Any help will do.

Answer Source

json.dumps and dump have a parameter called indent

If ``indent`` is a non-negative integer, then JSON array elements and
    object members will be pretty-printed with that indent level. An indent
    level of 0 will only insert newlines. ``None`` is the most compact
    representation.  Since the default item separator is ``', '``,  the
    output might include trailing whitespace when ``indent`` is specified.
    You can use ``separators=(',', ': ')`` to avoid this

Something like this would do: