To pretty-print a JSON file in Python, use the built-in json
module with the indent
parameter. Here’s a step-by-step solution:
Method 1: Read and Pretty-Print a JSON File
import json
# Read JSON data from a file
with open("input.json", "r") as file:
data = json.load(file)
# Convert to pretty-printed JSON string
pretty_json = json.dumps(data, indent=4, sort_keys=True)
# Print or save to a file
print(pretty_json) # Display in console
# Save to a new file
with open("pretty_output.json", "w") as file:
json.dump(data, file, indent=4, sort_keys=True)
Method 2: Pretty-Print a JSON String
If you already have a JSON string:
import json
json_string = '{"name": "Alice", "age": 30, "city": "Paris"}'
data = json.loads(json_string) # Parse string to dict
pretty_json = json.dumps(data, indent=4)
print(pretty_json)
Key Parameters
Parameter | Description |
---|---|
indent=4 | Number of spaces for indentation (use None for compact format) |
sort_keys=True | Sort keys alphabetically (optional) |
ensure_ascii=False | Display non-ASCII characters (e.g., é, ü) instead of escaping them |
Example Output
Original JSON (input.json
):
{"name": "Alice", "age": 30, "city": "Paris", "hobbies": ["coding", "hiking"]}
Pretty-Printed Result:
{
"age": 30,
"city": "Paris",
"hobbies": [
"coding",
"hiking"
],
"name": "Alice"
}
Bonus: Command-Line Method
Use Python’s json.tool
module directly from the terminal:
# Pretty-print a JSON file
python -m json.tool input.json
# Save to a new file
python -m json.tool input.json > pretty_output.json
Common Issues & Fixes
JSONDecodeError
: Invalid JSON syntax. Validate your JSON first (e.g., JSONLint).- Non-serializable objects: Use
default=str
injson.dumps()
to handle non-serializable types (e.g.,datetime
). - Unicode characters: Add
ensure_ascii=False
to preserve special characters.
This approach efficiently formats JSON for readability while maintaining compatibility with Python’s standard library.