Write JSON data to a file in Python

Use json.dump with UTF-8, distinguish JSON documents from JSON Lines, and handle Unicode, dates, and strict numeric serialization deliberately.

Best practices
Python programming and application logging

Use json.dump(data, file) to serialize a Python value directly to a text file. Specify UTF-8 when opening the file and choose indentation based on whether people will read it.

import json

data = {"name": "Zoë", "age": 35, "city": "Montréal"}
with open("data.json", "w", encoding="utf-8") as output:
    json.dump(data, output, indent=4, ensure_ascii=False, allow_nan=False)

The context manager closes the file. ensure_ascii=False keeps non-ASCII characters visible rather than writing Unicode escapes. Both representations can express the same decoded strings. allow_nan=False rejects non-finite floats that are not valid JSON numbers.

Read it back

with open("data.json", "r", encoding="utf-8") as source:
    restored = json.load(source)
print(restored["name"])  # Zoë

JSON object keys are strings. Some Python values, such as tuples, round-trip into different types, and custom objects need an explicit serialization policy.

dump versus dumps

json.dump() writes to a file-like object's write() method. json.dumps() returns a JSON string that you can send or store elsewhere:

serialized = json.dumps(data, ensure_ascii=False)
print(type(serialized).__name__)  # str

Omitting indent avoids pretty-printing line breaks, but does not remove every optional space. Use separators=(",", ":") when you specifically need compact separators.

Write JSON Lines for a sequence of records

records = [{"event": "start"}, {"event": "finish"}]
with open("data.jsonl", "w", encoding="utf-8") as output:
    for record in records:
        output.write(json.dumps(record, ensure_ascii=False, allow_nan=False) + "\n")

Each physical line is one JSON value. Do not use indented multi-line serialization for this format. Repeatedly calling dump() into an ordinary JSON file does not automatically create a valid array or separate document framing.

FAQ

How do I serialize datetime? Convert it to an explicitly chosen representation, such as an aware datetime's isoformat() string, or implement a custom encoder. Decoding that string will not automatically recreate a datetime object.

What happens if the file already exists? Mode "w" truncates it. Mode "a" can append JSON Lines records, but blindly appending another object to a JSON document makes it invalid. For a file that must survive interrupted updates, write a temporary file and replace the destination using a suitable filesystem strategy.

Why do I still see Unicode escapes? They are valid JSON, not inherently corrupt data. Use ensure_ascii=False for readability and decode the file as UTF-8.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting