1

I would like to save a list of python dicts A into a JSON file B. I used

json.dump(A, B)

to do that. But the saved JSON file's format is like

[{'a': 1, 'b': 1}, {'a':2, 'b':2}...]

What I want the display is to be something like:

[ 
 {'a': 1, 'b': 1},
 {'a': 2, 'b': 2},
 ...
], 

so that others can easily read. Is there a way to do that?

1 Answers1

4

You can use the indent argument when using json.dumps (see end of section in link):

If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as "\t"), that string is used to indent each level.

>>> print(json.dumps({1:'a', 2: 'b'}, indent=1))
{
 "1": "a",
 "2": "b"
}
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88