Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving dict as JSON so that they are human readable [duplicate]

When a dict is saved using json.dump, it is only a single-line. I want to make this a human-readable format such as this website does - https://jsonformatter.curiousconcept.com

How can I do this in python? I tried to capture pprint output, but it is an invalid string to store JSON in.

Specifically, is there an acceptable default way to do this in python directly?

like image 324
goelakash Avatar asked Mar 16 '16 18:03

goelakash


1 Answers

You should utilize the indent and separators parameters in the json module. From the docs there:

>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True,
...                  indent=4, separators=(',', ': '))
{
    "4": 5,
    "6": 7
}
like image 171
Ami Tavory Avatar answered Sep 20 '22 15:09

Ami Tavory