Use the built-in json.dump() function inside a with open() context manager to serialize a Python object and write it directly to a file. Using with guarantees the file is properly closed after writing, even if an error occurs.

Basic Example

import json

# 1. Define a Python dictionary or list
user_data = {
    "id": 101,
    "name": "Aisha Khan",
    "roles": ["admin", "editor"],
    "active": True
}

# 2. Open the file in write mode with UTF-8 encoding and serialize the data
with open("user_data.json", "w", encoding="utf-8") as file:
    json.dump(user_data, file, indent=4)

Key Details & Parameters

  • Explicit UTF-8 encoding: Always pass encoding="utf-8" to open() so your code behaves consistently across Windows, macOS, and Linux, especially when storing non-ASCII text.
  • Human-readable formatting (indent): By default, json.dump() writes everything on a single compact line. Passing indent=4 (or indent=2) pretty-prints the output with indentation; omit indent in production if minimizing file size matters more than readability.
  • Preserving non-ASCII characters (ensure_ascii=False): By default, Python escapes non-ASCII characters into \uXXXX sequences. Pass ensure_ascii=False to write native Unicode characters (such as Urdu, Arabic, emojis, or accented letters) directly into the file:
    with open("greetings.json", "w", encoding="utf-8") as file:
        json.dump({"message": "السلام علیکم"}, file, ensure_ascii=False, indent=4)
    
  • Deterministic key order (sort_keys=True): Sorts dictionary keys alphabetically in the output file, which is useful when tracking JSON files in Git version control.

json.dump() vs. json.dumps()

Function Target Output Best Used When
json.dump(obj, file) Writes directly to a file-like stream Saving JSON data directly to disk.
json.dumps(obj) Returns a formatted JSON str Sending JSON over an API, logging, or manipulating the string before saving.

Frequently Asked Questions

Why do I get TypeError: Object of type set is not JSON serializable?
Standard JSON only supports objects (dict), arrays (list/tuple), strings (str), numbers (int/float), booleans (True/False), and null (None). Convert unsupported types like set into a list first, or pass a custom default serializer function (e.g., json.dump(data, file, default=str) for datetime objects).

How do I append new data to an existing JSON file?
You cannot simply open a JSON file in "a" (append) mode because that breaks the outer {} or [] syntax. Instead, read the existing file with json.load(), update the Python list or dictionary in memory, and overwrite the file using json.dump().