How to Write a Dict to a Pretty JSON File with Indent in Python
Serializes a Python dictionary to a readable JSON file using json.dump with indentation and sorted keys, then prints the file contents to stdout.
Python code
17 linesimport json
from pathlib import Path
data = {
"name": "Python",
"version": 3.12,
"features": ["simple", "readable", "powerful"],
"nested": {"creator": "Guido van Rossum", "year": 1991}
}
output_path = Path("output.json")
with output_path.open("w", encoding="utf-8") as f:
json.dump(data, f, indent=4, sort_keys=True)
print(f"Written to {output_path}")
print(output_path.read_text(encoding="utf-8"))
Output
Written to output.json
{
"name": "Python",
"version": 3.12,
"features": [
"simple",
"readable",
"powerful"
],
"nested": {
"creator": "Guido van Rossum",
"year": 1991
}
}
How it works
The json.dump call writes the dictionary directly to the file object, with indent=4 adding four spaces per nesting level and sort_keys=True ordering keys alphabetically for stable, consistent output. Using Path.open in a with statement guarantees the file is closed properly even if an error occurs. The encoding is set to UTF-8, which is the default for JSON and safe for non-ASCII characters. The final read_text call verifies the written content by displaying it back to the console.
Common mistakes
- Using `json.dumps` and forgetting to write the resulting string manually instead of `json.dump` for direct file writing.
- Omitting `encoding='utf-8'` which can cause issues with non-ASCII characters on some platforms.
- Forgetting to close the file if not using a `with` block, leaking file handles.
- Confusing `indent` with `separators` — indent only affects whitespace, separators control delimiters.
Variations
- Use `json.dump(data, f, indent=2)` for a more compact but still readable format.
- Write to a string with `json.dumps(data, indent=4, sort_keys=True)` if you need to pass it elsewhere.
Real-world use cases
- Exporting configuration or settings dicts from a web app to a human-readable config file on the server.
- Persisting analysis results or model outputs from a data pipeline as readable JSON for easy inspection and sharing.
- Creating fixture files for automated tests that need stable, nicely formatted JSON data to assert against.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.