How to prettyprint (human readably print) a Python dict in json format (double quotes)? [duplicate]
Asked Answered
M

1

31

This is a follow-up question to this one. I need to both prettyprint a python dict (so I can visually inspect/modify it), and I need to have the output in json format (with the double quotes).

pprint module prettyprints the dict but uses single quotes (not json!). That's the topic of the linked other question/answer.

json.dumps will use the double quotes, but prints it in a big line (not human readable!)

How can we achieve both?

Marlee answered 15/3, 2016 at 20:19 Comment(0)
F
53

See the docs:

import json

print(json.dumps(
    {'4': 5, '6': 7},
    sort_keys=True,
    indent=4,
    separators=(',', ': ')
))
Furr answered 15/3, 2016 at 20:21 Comment(4)
While it would convert the None object to null which raise null was not a object exceptionMonodic
You might want to add ensure_ascii=False, otherwise unicode characters will look like \u0435.Seaward
@RyanChou you can do null = None before importing/copy pasting the result to avoid the exception.Seaward
In python3.4+, no need to specify separators as (',', ': ') as that is the default (even if indent is not None)Thitherto

© 2022 - 2024 — McMap. All rights reserved.