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.

Easy Python 3.9+ Aug 9, 2026 Files & data 14 views 0 copies

Python code

17 lines
Python 3.9+
import 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

stdout
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

  1. Use `json.dump(data, f, indent=2)` for a more compact but still readable format.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.