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?

0

1 Answer 1

5

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"
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.