Sometimes, we want to pretty print a JSON file with Python.
In this article, we’ll look at how to pretty print a JSON file with Python.
How to pretty print a JSON file with Python?
To pretty print a JSON file with Python, we can use the json.dumps
method with the indent
argument.
For instance, we write
import json
your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
parsed = json.loads(your_json)
print(json.dumps(parsed, indent=4, sort_keys=True))
to call json.loads
with your_json
to load it into an object.
Then we call json.dumps
with the parsed
JSON object and indent
set to 4 to return a JSON string 4 spaces to indent each level.
Conclusion
To pretty print a JSON file with Python, we can use the json.dumps
method with the indent
argument.