How to Pretty Print JSON in Python: Simple Guide
To pretty print JSON in Python, use the
json.dumps() function with the indent parameter set to a number of spaces for indentation. This formats the JSON string with line breaks and indentation for easy reading.Syntax
The basic syntax to pretty print JSON in Python uses the json.dumps() function with the indent argument. Here is what each part means:
json.dumps(obj): Converts a Python objectobjto a JSON string.indent=number: Adds line breaks and spaces to format the JSON output. The number sets how many spaces to use for each indentation level.
python
import json json_string = json.dumps(obj, indent=4)
Example
This example shows how to pretty print a Python dictionary as JSON with 4 spaces indentation. It makes the JSON output easy to read by adding new lines and spaces.
python
import json # Sample Python dictionary person = { "name": "Alice", "age": 30, "city": "New York", "hobbies": ["reading", "hiking", "coding"] } # Convert to pretty printed JSON string pretty_json = json.dumps(person, indent=4) # Print the formatted JSON print(pretty_json)
Output
{
"name": "Alice",
"age": 30,
"city": "New York",
"hobbies": [
"reading",
"hiking",
"coding"
]
}
Common Pitfalls
Some common mistakes when pretty printing JSON in Python include:
- Forgetting to import the
jsonmodule. - Not using
json.dumps()but trying to print the Python object directly, which won't format as JSON. - Using
print(json.dumps(obj))withoutindentwill print JSON in one line, not pretty. - Confusing
json.dumps()(returns string) withjson.dump()(writes to file).
Example of wrong and right way:
python
import json data = {"key": "value"} # Wrong: prints Python dict, not JSON string print(data) # Wrong: JSON string but no pretty print print(json.dumps(data)) # Right: pretty print with indent print(json.dumps(data, indent=2))
Output
{'key': 'value'}
{"key": "value"}
{
"key": "value"
}
Quick Reference
Tips for pretty printing JSON in Python:
- Use
json.dumps(obj, indent=4)for readable JSON strings. - Use
indentvalue to control spaces per level. - Use
sort_keys=Trueto sort keys alphabetically. - Use
json.dump(obj, file, indent=4)to write pretty JSON directly to a file.
Key Takeaways
Use json.dumps() with indent parameter to pretty print JSON strings.
Indent controls the number of spaces for each level of nesting.
json.dumps() returns a string; use print() to display it.
json.dump() writes JSON directly to a file with optional pretty print.
Always import the json module before using its functions.