Last modified: May 28, 2026

Python JSON Dump String Guide

JSON is a popular data format for sharing information between systems. In Python, the json module makes it easy to work with JSON data. The json.dumps() function converts a Python object into a JSON string. This guide will show you how to use it effectively.

What is json.dumps()?

The json.dumps() function stands for "dump string." It takes a Python object and returns a JSON-formatted string. This is different from json.dump(), which writes directly to a file. Use json.dumps() when you need the JSON as a string for network transmission or further processing.

Think of it as a translator. It turns Python dictionaries, lists, and other objects into text that any program can understand.

Basic Usage of json.dumps()

Start by importing the json module. Then pass a Python object to json.dumps().


import json

# A simple Python dictionary
data = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# Convert to JSON string
json_string = json.dumps(data)
print(json_string)

{"name": "Alice", "age": 30, "city": "New York"}

Notice how the output is a single line. This is the default behavior. The keys and values are enclosed in double quotes, which is required by JSON.

Making JSON Output Pretty

For debugging or displaying data, a compact string is hard to read. Use the indent parameter to add whitespace.


import json

data = {
    "name": "Alice",
    "age": 30,
    "city": "New York",
    "hobbies": ["reading", "hiking"]
}

# Pretty print with 4 spaces indentation
pretty_json = json.dumps(data, indent=4)
print(pretty_json)

{
    "name": "Alice",
    "age": 30,
    "city": "New York",
    "hobbies": [
        "reading",
        "hiking"
    ]
}

The indent parameter makes the JSON structure clear. You can use 2 or 4 spaces. This is very helpful when you are learning or sharing data with others.

Sorting Keys for Consistency

Sometimes you need keys in alphabetical order. The sort_keys parameter does this.


import json

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

# Sort keys alphabetically
sorted_json = json.dumps(data, sort_keys=True, indent=2)
print(sorted_json)

{
  "age": 25,
  "city": "London",
  "name": "Bob"
}

This is useful for comparing JSON strings or when you need a predictable order.

Handling Different Data Types

The json.dumps() function can handle many Python types. It converts dictionaries, lists, strings, numbers, booleans, and None. But it cannot handle custom objects by default.


import json

# Mixed data types
data = {
    "active": True,
    "score": None,
    "grades": [90, 85, 88],
    "info": {"passed": True}
}

result = json.dumps(data, indent=2)
print(result)

{
  "active": true,
  "score": null,
  "grades": [
    90,
    85,
    88
  ],
  "info": {
    "passed": true
  }
}

Note that Python True becomes JSON true, and None becomes null. This is the correct JSON format.

Converting Custom Objects

If you have a Python class, you need to tell json.dumps() how to convert it. Use the default parameter with a function.


import json

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Custom conversion function
def person_to_dict(obj):
    return {"name": obj.name, "age": obj.age}

person = Person("Charlie", 35)
json_str = json.dumps(person, default=person_to_dict, indent=2)
print(json_str)

{
  "name": "Charlie",
  "age": 35
}

The default function receives the object and returns a dictionary. This dictionary is then serialized normally.

Common Errors and Solutions

One common error is trying to serialize unsupported types like datetime objects. The error message will say "Object of type datetime is not JSON serializable." To fix this, convert the object to a string first.


import json
from datetime import datetime

data = {
    "event": "meeting",
    "time": datetime.now()
}

# This will raise an error
# json.dumps(data)

# Solution: convert datetime to string
data["time"] = data["time"].isoformat()
json_str = json.dumps(data, indent=2)
print(json_str)

{
  "event": "meeting",
  "time": "2025-04-02T15:30:00.123456"
}

Always check that your data contains only JSON-compatible types. If not, convert them before calling json.dumps().

Using ensure_ascii for Non-ASCII Text

By default, json.dumps() escapes non-ASCII characters. Set ensure_ascii=False to keep them readable.


import json

data = {"name": "José", "city": "São Paulo"}

# Default: escapes non-ASCII
default_str = json.dumps(data)
print(default_str)

# With ensure_ascii=False
readable_str = json.dumps(data, ensure_ascii=False)
print(readable_str)

{"name": "Jos\u00e9", "city": "S\u00e3o Paulo"}
{"name": "José", "city": "São Paulo"}

Use ensure_ascii=False when you want human-readable output with special characters.

Practical Example: Saving and Loading Data

Here is a complete workflow. Convert a Python dictionary to a JSON string, then convert it back.


import json

# Original data
user = {
    "username": "john_doe",
    "email": "[email protected]",
    "is_admin": False
}

# Convert to JSON string
json_user = json.dumps(user, indent=2)
print("JSON string:")
print(json_user)

# Convert back to Python dictionary
parsed_user = json.loads(json_user)
print("\nParsed dictionary:")
print(parsed_user)

JSON string:
{
  "username": "john_doe",
  "email": "[email protected]",
  "is_admin": false
}

Parsed dictionary:
{'username': 'john_doe', 'email': '[email protected]', 'is_admin': False}

This round-trip is common in web applications. You send JSON to an API, receive it back, and parse it.

Best Practices for json.dumps()

Always use indent for debugging. Use sort_keys when you need consistent order. Convert custom objects with the default parameter. Handle non-ASCII text with ensure_ascii=False.

Test your JSON output with a validator. A small mistake can break data exchange between systems. Practice with different data types to build confidence.

Conclusion

The json.dumps() function is a powerful tool for converting Python objects to JSON strings. It is easy to use and flexible. With parameters like indent, sort_keys, and default, you can control the output exactly. Always check your data types to avoid serialization errors. Now you can handle JSON strings in Python with confidence.