Indentation breaks after saving updated json dict file to file

I have a nested dictionary with many elements 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 of each of the animals, and then save it back to the file, and save the indent as it was (as shown). I use the following 2 methods to load and reset the original and updated dictionary.

Everything works well (to change the value and save it back to the file), except that the indent (format) of the lines is destroyed after the file is saved, and the file is saved as one long line (with '\ n' displayed after the updated value).

I tried using "pickle" (as seen in one of the posts here), but it didn’t work, it messed up 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 would help.

+4
1

json.dumps dump , 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

- :

json.dump(jsonDict,f,indent=4)
+4

Source: https://habr.com/ru/post/1657042/


All Articles