PythonMastery

How do I write a dictionary to a JSON file in Python?

json.dump(data, f, indent=2) writes a readable file. ensure_ascii=False keeps accented names readable; default=str handles dates and other types JSON can't.

json.dump writes to an open file. Add indent=2 and a person can read the result too.

python
import json

settings = {"theme": "dark", "font_size": 14, "recent": ["notes.py", "app.py"]}

with open("settings.json", "w", encoding="utf-8") as f:
    json.dump(settings, f, indent=2)

with open("settings.json", encoding="utf-8") as f:
    print(f.read())
output
{
  "theme": "dark",
  "font_size": 14,
  "recent": [
    "notes.py",
    "app.py"
  ]
}

Want the text instead of a file, say to send in a request or write to a log? json.dumps(settings) returns it as a string.

Names that aren't plain English

By default every non-ASCII character is escaped, so Zoë is written as Zo\u00eb. It's valid, but nobody can read it. ensure_ascii=False keeps the real characters; keep encoding="utf-8" on the file when you use it.

python
import json

print(json.dumps({"name": "Zoë", "city": "São Paulo"}))
print(json.dumps({"name": "Zoë", "city": "São Paulo"}, ensure_ascii=False))
output
{"name": "Zo\u00eb", "city": "S\u00e3o Paulo"}
{"name": "Zoë", "city": "São Paulo"}

"Object of type date is not JSON serializable"

JSON only knows strings, numbers, booleans, null, lists and objects. A date, a Decimal or a set has no JSON form, so dump refuses.

python
import json
from datetime import date

order = {"id": "A-1001", "placed": date(2026, 10, 7)}

try:
    json.dumps(order)
except TypeError as e:
    print(e)

print(json.dumps(order, default=str))
output
Object of type date is not JSON serializable
{"id": "A-1001", "placed": "2026-10-07"}

default=str means "for anything you can't handle, use its string form". For dates that gives ISO format, which every language can parse back. For a set, convert it with list() yourself first.

Go deeper: CSV, JSON, and JSONL — Structured Text Done Right, Dictionaries

More short answers

all questions