Last modified: May 28, 2026

Python Dump Object to JSON Guide

Serializing Python objects to JSON is a common task for data exchange and storage. The json module provides two main functions: json.dump() for writing directly to a file and json.dumps() for converting to a JSON string. This guide covers both methods with clear examples for beginners.

Why Serialize Python Objects?

JSON (JavaScript Object Notation) is a lightweight data format used by APIs, configuration files, and databases. Converting Python objects to JSON makes them portable across different systems and languages. You can save data to disk, send it over a network, or share it with other applications.

Python's json module handles most built-in types like dict, list, string, int, float, bool, and None. For custom objects, you need to write custom serializers, but the basics are straightforward.

Using json.dump() for File Output

The json.dump() function writes a Python object directly to a file. It takes two required arguments: the object to serialize and the file object opened for writing.

import json

data = {
    "name": "Alice",
    "age": 30,
    "skills": ["Python", "Data Analysis", "Machine Learning"],
    "active": True
}

# Open a file for writing JSON
with open("data.json", "w") as file:
    json.dump(data, file)
print("Data written to data.json")

This creates a file named data.json with the JSON representation. The file must be opened in write mode ("w") for text output. For binary files, use "wb" but JSON is typically text.

Using json.dumps() for String Output

The json.dumps() function returns a JSON string instead of writing to a file. Use this when you need to store the JSON in a variable, send it as an API response, or embed it in another text format.

import json

data = {
    "name": "Bob",
    "age": 25,
    "city": "New York"
}

json_string = json.dumps(data)
print(json_string)
{"name": "Bob", "age": 25, "city": "New York"}

The output is a single-line string. For readability, you can add formatting options like indent and sort_keys.

Pretty Printing with Indentation

To make JSON output more human-readable, use the indent parameter. This adds whitespace and newlines to structure the output.

import json

data = {
    "name": "Charlie",
    "age": 35,
    "address": {
        "street": "123 Main St",
        "city": "Boston",
        "zip": "02101"
    }
}

# Pretty print with 4 spaces indentation
json_string = json.dumps(data, indent=4)
print(json_string)
{
    "name": "Charlie",
    "age": 35,
    "address": {
        "street": "123 Main St",
        "city": "Boston",
        "zip": "02101"
    }
}

You can also use sort_keys=True to alphabetically order the keys. This is useful for consistent output in version control or comparisons.

Handling Non-Serializable Types

Python objects like datetime, Decimal, or custom classes cannot be serialized by default. You'll get a TypeError. The solution is to use the default parameter with a custom function.

import json
from datetime import datetime

def custom_serializer(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()
    raise TypeError(f"Type {type(obj)} not serializable")

data = {
    "event": "Conference",
    "date": datetime(2025, 6, 15, 14, 30, 0)
}

json_string = json.dumps(data, default=custom_serializer)
print(json_string)
{"event": "Conference", "date": "2025-06-15T14:30:00"}

Alternatively, you can subclass json.JSONEncoder for reusable serializers. This keeps your code clean and modular.

Common Options for json.dump() and json.dumps()

Both functions accept additional parameters to control output. Here are the most useful ones:

  • indent: Number of spaces for indentation (e.g., indent=2).
  • sort_keys: Boolean to sort dictionary keys alphabetically.
  • separators: Tuple of (item_separator, key_separator) to reduce whitespace (e.g., (',', ':') for compact output).
  • ensure_ascii: If True (default), non-ASCII characters are escaped. Set to False to allow Unicode.
  • default: Function to handle non-serializable objects.

For example, to create a compact JSON string with no extra spaces:

compact = json.dumps(data, separators=(',', ':'))
print(compact)
{"name":"Charlie","age":35,"address":{"street":"123 Main St","city":"Boston","zip":"02101"}}

Reading JSON Back to Python

After dumping, you'll often need to load the JSON back. Use json.load() for files and json.loads() for strings. This completes the serialization cycle.

import json

# From string
json_string = '{"name": "Diana", "age": 28}'
data = json.loads(json_string)
print(data["name"])  # Outputs: Diana

# From file
with open("data.json", "r") as file:
    data = json.load(file)
print(data)

Always handle file operations with context managers (with statement) to ensure proper resource cleanup.

Best Practices for JSON Serialization

Follow these tips to avoid common pitfalls:

  • Validate data types before serialization. JSON supports only: dict, list, str, int, float, bool, None.
  • Use ensure_ascii=False when working with non-English text to keep characters readable.
  • Set indent for development and remove it for production to save space.
  • Test with edge cases like empty dicts, nested structures, and large datasets.
  • Consider security when loading JSON from untrusted sources. Use json.loads() with caution.

If you're working with custom classes, consider using libraries like dataclasses with dataclasses_json for automatic serialization. For complex projects, Pydantic provides robust validation and serialization.

Conclusion

Python's json.dump() and json.dumps() are essential tools for converting Python objects to JSON. With simple syntax and flexible options, you can handle file storage, API communication, and data exchange efficiently. Remember to handle non-serializable types with custom functions and follow best practices for clean, reliable code. Practice with different data structures to master serialization in your projects.