Python
JSON
Pretty-Print
File Handling
Programming Tutorial

Pretty-Print JSON Data to a File using Python

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Pretty-printing JSON to a file in Python is straightforward with the standard json module, but the details matter if you care about readability, stable diffs, or safe writes. The right implementation depends on whether the file is just for debugging or is part of a repeatable build, configuration, or state-management workflow.

Use json.dump With Indentation

The basic way to write readable JSON is to call json.dump with an indent value.

python
1import json
2
3payload = {
4    "service": "billing",
5    "enabled": True,
6    "retry": 3,
7    "hosts": ["api-1", "api-2"],
8}
9
10with open("config.json", "w", encoding="utf-8") as f:
11    json.dump(payload, f, indent=2)

This already produces readable multi-line JSON. For many local debugging tasks, that is enough.

Make the Output Stable for Diffs

If the file will be committed to version control or compared across runs, deterministic ordering matters as much as indentation.

python
1import json
2
3data = {
4    "z": 1,
5    "a": 2,
6    "nested": {"b": 3, "a": 4},
7}
8
9with open("stable.json", "w", encoding="utf-8") as f:
10    json.dump(
11        data,
12        f,
13        indent=2,
14        sort_keys=True,
15        ensure_ascii=False,
16        separators=(",", ": "),
17    )
18    f.write("\n")

The trailing newline and key sorting help keep diffs clean and predictable.

Handle Non-JSON Python Types Explicitly

Objects such as datetime, Decimal, or custom classes are not serializable by default. If those appear in the data, provide a conversion function.

python
1import json
2from datetime import datetime
3from decimal import Decimal
4
5
6def encode_custom(obj):
7    if isinstance(obj, datetime):
8        return obj.isoformat()
9    if isinstance(obj, Decimal):
10        return str(obj)
11    raise TypeError(f"Unsupported type: {type(obj).__name__}")
12
13
14payload = {
15    "created_at": datetime(2026, 3, 11, 12, 0, 0),
16    "price": Decimal("19.99"),
17}
18
19with open("custom.json", "w", encoding="utf-8") as f:
20    json.dump(payload, f, indent=2, default=encode_custom)

Do not ignore these failures or silently coerce them without deciding what representation is correct for the consumer of the file.

Use Safer Writes for Important Files

If the file is important state rather than disposable debug output, writing directly to the destination path can leave a corrupted partial file if the process stops mid-write. A safer pattern is to write to a temporary file and then replace the target atomically.

python
1import json
2import os
3import tempfile
4
5
6def write_json_atomic(path, data):
7    directory = os.path.dirname(path) or "."
8
9    with tempfile.NamedTemporaryFile("w", dir=directory, delete=False, encoding="utf-8") as tmp:
10        json.dump(data, tmp, indent=2, sort_keys=True, ensure_ascii=False)
11        tmp.write("\n")
12        temp_path = tmp.name
13
14    os.replace(temp_path, path)
15
16
17write_json_atomic("state.json", {"status": "ok", "count": 7})

This is a better default for configuration, cache, or state files that another process may read.

Reformat Existing JSON Cleanly

A common task is to read minified or inconsistently formatted JSON and rewrite it in one canonical style.

python
1import json
2
3with open("input.json", "r", encoding="utf-8") as f:
4    obj = json.load(f)
5
6with open("output_pretty.json", "w", encoding="utf-8") as f:
7    json.dump(obj, f, indent=2, sort_keys=True, ensure_ascii=False)
8    f.write("\n")

That is a simple way to normalize generated files or prepare machine-produced JSON for human review.

For many scripts, the standard library is enough. You usually do not need a third-party formatter unless the workflow also requires schema validation, comments, or other non-standard JSON features.

Common Pitfalls

A common mistake is assuming indentation alone makes the output good enough for long-term use. If the file participates in tests or code review, stable key ordering often matters too.

Another issue is forgetting that some Python objects are not JSON-native. Pretty printing cannot fix serialization errors by itself.

Developers also often overwrite important files directly when they should be using a safer temporary-file pattern.

Finally, pretty formatting does not guarantee semantic correctness. The JSON can be beautifully indented and still contain the wrong data.

Summary

  • Use json.dump with indent to write readable JSON files.
  • Add sort_keys=True and a trailing newline when stable diffs matter.
  • Provide a custom serializer for non-JSON Python types.
  • Use atomic replace patterns when file integrity matters.
  • Treat pretty printing as formatting, not as a substitute for validation.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.