python
json
dictionary
file-handling
tutorial

How to dump a dict to a JSON file?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Writing a Python dictionary to a JSON file is one of the simplest persistence tasks in the standard library. The basic tool is json.dump, but quality comes from handling encoding, formatting, and non-JSON-native values correctly. A small amount of care keeps the output readable and avoids surprises later when the file is loaded again.

Use json.dump with a File Handle

The standard pattern is to open a file in text mode and pass both the dictionary and the file object to json.dump.

python
1import json
2
3data = {
4    "name": "Ava",
5    "age": 31,
6    "skills": ["python", "sql", "pandas"],
7}
8
9with open("profile.json", "w", encoding="utf-8") as file:
10    json.dump(data, file)

This writes compact JSON to profile.json. The with block ensures the file closes cleanly even if an exception occurs.

Make the Output Human-Readable

For config files, fixtures, or debug output, compact JSON is harder to inspect. Adding indentation makes the file much easier to read.

python
1import json
2
3data = {
4    "project": "analytics",
5    "active": True,
6    "owners": ["Ava", "Mina"],
7}
8
9with open("config.json", "w", encoding="utf-8") as file:
10    json.dump(data, file, indent=2)

This is usually the right default for files that humans may open directly.

Preserve Non-ASCII Characters When Needed

By default, Python escapes non-ASCII characters. That is valid JSON, but it can make output harder to read for real text data. Setting ensure_ascii=False keeps UTF-8 characters readable.

python
1import json
2
3data = {
4    "city": "Montréal",
5    "message": "Olá",
6}
7
8with open("localized.json", "w", encoding="utf-8") as file:
9    json.dump(data, file, indent=2, ensure_ascii=False)

Because the file is opened with UTF-8 encoding, the text is written cleanly and remains portable.

Know What JSON Can and Cannot Store

JSON supports objects, arrays, strings, numbers, booleans, and null. A normal Python dict maps cleanly to a JSON object, but not every Python value is serializable by default.

For example, this will fail:

python
1import json
2from datetime import datetime
3
4data = {"created_at": datetime.now()}
5
6with open("broken.json", "w", encoding="utf-8") as file:
7    json.dump(data, file)

To handle custom or unsupported values, provide a conversion function:

python
1import json
2from datetime import datetime
3
4def default_converter(value):
5    if isinstance(value, datetime):
6        return value.isoformat()
7    raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable")
8
9data = {"created_at": datetime.now()}
10
11with open("events.json", "w", encoding="utf-8") as file:
12    json.dump(data, file, indent=2, default=default_converter)

This is the usual way to serialize datetimes, decimals, and application-specific types.

Dump to a String First When Helpful

Sometimes you want the JSON text before writing it, for logging or testing. In that case, json.dumps is the string-producing version.

python
1import json
2
3data = {"status": "ok", "count": 3}
4json_text = json.dumps(data, indent=2)
5
6with open("status.json", "w", encoding="utf-8") as file:
7    file.write(json_text)

For direct file output, json.dump is simpler. json.dumps is useful when the JSON string itself has value before it reaches the filesystem.

Write Safely for Important Files

If the file is important and partial writes would be a problem, writing to a temporary file first and then replacing the target can be safer than writing directly. That pattern matters for config updates and caches used by multiple processes.

The important idea is not that JSON needs special handling. It is that file replacement can be safer than in-place overwrite when corruption matters.

Common Pitfalls

  • Forgetting to open the file with encoding="utf-8" when text data may contain non-ASCII characters.
  • Writing unreadable one-line JSON when the file is meant for humans.
  • Assuming every Python object can be serialized without a custom converter.
  • Confusing json.dump with json.dumps.
  • Writing directly to a critical file when a safer replace strategy would reduce corruption risk.

Summary

  • Use json.dump to write a dictionary directly to a JSON file.
  • Add indent when humans may read the file.
  • Use ensure_ascii=False with UTF-8 when readable non-ASCII text matters.
  • Supply a default converter for unsupported Python types.
  • Use json.dumps only when you specifically need the JSON as a string first.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

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

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.