Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 711
travelingbones Avatar asked Mar 15 '16 20:03

travelingbones


People also ask

How do you write JSON format in Python?

Method 2: Writing JSON to a file in Python using json.dump() Another way of writing JSON to a file is by using json. dump() method The JSON package has the “dump” function which directly writes the dictionary to a file in the form of JSON, without needing to convert it into an actual JSON object.

How do I prettify JSON?

Use JSON. stringify(obj) method to convert JavaScript objects into strings and display it. Use JSON. stringify(obj, replacer, space) method to convert JavaScript objects into strings in pretty format.


1 Answers

See the docs:

import json

print(json.dumps(
    {'4': 5, '6': 7},
    sort_keys=True,
    indent=4,
    separators=(',', ': ')
))
like image 120
Jérôme Avatar answered Sep 22 '22 22:09

Jérôme