pythonjsonformatter

Save a Python dict as a JSON file

Write data to a portable UTF-8 JSON file with a standard-library function and predictable formatting.

Write JSON with json.dump()

json.dump() serializes a Python value directly into an open file. It avoids creating a large intermediate string when you only need a file.

import json

data = {"project": "formatter", "published": True, "city": "Madrid"}

with open("data.json", "w", encoding="utf-8") as file:
    json.dump(data, file, indent=2, ensure_ascii=False)

The file contains JSON values, not Python spellings: True becomes true. Opening with "w" replaces an existing file of the same name, so choose the path deliberately.

{
  "project": "formatter",
  "published": true,
  "city": "Madrid"
}

Formatting decisions

indent=2 makes a file easier to review in a code editor. ensure_ascii=False keeps supported Unicode characters readable instead of escaping them. Use sort_keys=True only when stable key ordering helps reviews or reproducible output.

NeedOption
Readable nested JSONindent=2
Readable Unicode textensure_ascii=False
Stable orderingsort_keys=True

Read the same file back

with open("data.json", encoding="utf-8") as file:
    restored = json.load(file)

assert restored == data
print(restored["published"])  # True

Use a context manager so Python closes the file even when parsing or writing fails. If a value is not JSON-serializable, convert it before writing instead of silently changing its meaning. A failed write can leave a partial file; for important configuration files, write to a temporary file and replace the destination only after serialization succeeds.

Exporting one record per line? Follow the JSON Lines reader and writer instead of concatenating JSON documents. For escaped characters or damaged text, see Unicode escapes and file encoding.

By Python JSON Formatter ·