10

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?

4

1 Answer 1

10

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
}
4
  • why is your value ident 4 and not some other value? Commented Oct 16, 2020 at 20:03
  • 1
    @CharlieParker It's a common value (indent 4 spaces). You can set it to something else, if you want.
    – Ami Tavory
    Commented Oct 16, 2020 at 20:11
  • why do you need separators=(',', ': ')? Commented Oct 16, 2020 at 20:12
  • I ended up using: json.dump(args_data, argsfile, indent=4) Commented Oct 16, 2020 at 20:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.