MarkS MarkS - 17 days ago 6
JSON Question

Print a list of dictionaries to a file

Python 3.6

I have a program that is generating a list of dictionaries.

If I print it to the screen with:

print(json.dumps(output_lines, indent=4, separators=(',', ': ')))


It prints out exactly as I want to see it:

[
{
"runts": 0,
"giants": 0,
"throttles": 0,
"input errors": 0,
"CRC": 0,
"frame": 0,
"overrun": 0,
"ignored": 0,
"watchdog": 0,
"pause input": 0,
"input packets with dribble condition detected": 0,
"underruns": 0,
"output errors": 0,
"collisions": 0,
"interface resets": 2,
"babbles": 0,
"late collision": 0,
"deferred": 0,
"lost carrier": 0,
"no carrier": 0,
"PAUSE output": 0,
"output buffer failures": 0,
"output buffers swapped out": 0
},
{
"runts": 0,
"giants": 0,
"throttles": 0,
"input errors": 0,
"CRC": 0,
"frame": 0,
"overrun": 0,
"ignored": 0,
"watchdog": 0,
"pause input": 0,
"input packets with dribble condition detected": 0,
"underruns": 0,
"output errors": 0,
"collisions": 0,
"interface resets": 2,
"babbles": 0,
"late collision": 0,
"deferred": 0,
"lost carrier": 0,
"no carrier": 0,
"PAUSE output": 0,
"output buffer failures": 0,
"output buffers swapped out": 0
},


But if I try to print it to a file with:

outputfile = ("d:\\mark\\python\\Projects\\error_detect\\" + hostname)
# print(json.dumps(output_lines, indent=4, separators=(',', ': ')))
output_lines.append(json.dumps(output_lines, indent=4, separators=(',', ': ')))
del output_lines[-1]
with open(outputfile, 'w') as f:
json.dump(output_lines, f)


The file is one giant line of text.

I want the formatting in the file to look like it does when I print to the screen.

I do not understand why I am losing the formatting.

Answer

Say your program generates this list of dictionaries

>>> list_of_dicts = [dict(zip(list(range(2)),list(range(2)))), dict(zip(list(range(2)),list(range(2))))]
>>> list_of_dicts
[{0: 0, 1: 1}, {0: 0, 1: 1}]

What you can do is

>>> import json
>>> str_object = json.dumps(list_of_dicts, indent=4)
>>> repr(str_object)
'[\n    {\n        "0": 0, \n        "1": 1\n    }, \n    {\n        "0": 0, \n        "1": 1\n    }\n]'
>>> str_object
[
    {
        "0": 0, 
        "1": 1
    }, 
    {
        "0": 0, 
        "1": 1
    }
]

Now you can write str_object

>>> with open(outputfile, 'w') as f:
        f.write(str_object)

Which makes the formatting in the file be as it is when you print it to the screen.