Skip to main content

What Are the Differences Between json.dump() and json.dumps() in Python

Python's json module provides two functions for converting Python objects to JSON format: json.dump() and json.dumps(). The difference is simple but important: the "s" in dumps stands for "string." One writes JSON to a string in memory, the other writes JSON directly to a file. This same naming convention applies to their counterparts for reading JSON: json.loads() reads from a string, and json.load() reads from a file.

This guide explains when to use each function, covers their shared formatting options, and shows how to handle common serialization challenges.

json.dumps(): Serialize to a String

json.dumps() converts a Python object into a JSON-formatted string and returns it. Use this when you need the JSON data in memory, such as for API responses, logging, or passing data between functions:

import json

data = {"name": "Alice", "age": 30, "active": True}

json_string = json.dumps(data)
print(json_string)
print(type(json_string))

Output:

{"name": "Alice", "age": 30, "active": true}
<class 'str'>

The result is a plain Python string that you can store in a variable, send over a network, or process further.

json.dump(): Serialize Directly to a File

json.dump() writes the JSON output directly to a file object instead of returning a string. This is more memory-efficient for large datasets because it does not need to create an intermediate string in memory:

import json

data = {"name": "Alice", "age": 30, "active": True}

with open("data.json", "w") as f:
json.dump(data, f)

After running this code, the file data.json contains:

{"name": "Alice", "age": 30, "active": true}

Notice the key difference in the function signatures: json.dumps(data) takes just the data object, while json.dump(data, f) takes the data object and a file object as its second argument.

Formatting Options (Shared by Both Functions)

Both json.dump() and json.dumps() accept the same formatting parameters. The examples below use json.dumps() to show the output directly, but every parameter works identically with json.dump():

Pretty Printing with Indentation

import json

data = {"name": "Alice", "scores": [95, 87, 92]}

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

Output:

{
"name": "Alice",
"scores": [
95,
87,
92
]
}

Sorting Keys Alphabetically

import json

data = {"name": "Alice", "scores": [95, 87, 92], "age": 30}

print(json.dumps(data, sort_keys=True, indent=2))

Output:

{
"age": 30,
"name": "Alice",
"scores": [
95,
87,
92
]
}

Compact Output (Minimal Whitespace)

import json

data = {"name": "Alice", "scores": [95, 87, 92]}

print(json.dumps(data, separators=(",", ":")))

Output:

{"name":"Alice","scores":[95,87,92]}

This removes all unnecessary whitespace, which is useful when minimizing payload size for network transmission.

Writing a Pretty-Printed File

import json

data = {"name": "Alice", "scores": [95, 87, 92]}

with open("data_pretty.json", "w") as f:
json.dump(data, f, indent=2, sort_keys=True)

The Reverse: json.loads() and json.load()

The same naming pattern applies to deserialization. Functions with "s" work with strings, functions without "s" work with files:

import json

# From a string
json_string = '{"name": "Alice", "age": 30}'
data_from_string = json.loads(json_string)
print(data_from_string)

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

Output:

{'name': 'Alice', 'age': 30}
{'name': 'Alice', 'age': 30}
tip

Remember the pattern: functions ending in "s" work with strings. Functions without "s" work with file objects. This applies to all four functions: dump/dumps and load/loads.

Handling Non-Serializable Types

JSON only supports a limited set of types (strings, numbers, booleans, null, arrays, and objects). If your Python object contains types like datetime, set, or custom classes, both dump() and dumps() raise a TypeError:

import json
from datetime import datetime

data = {"event": "login", "timestamp": datetime.now()}

# This fails
try:
json.dumps(data)
except TypeError as e:
print(f"Error: {e}")

Output:

Error: Object of type datetime is not JSON serializable

Quick Fix with default=str

The simplest workaround is to pass default=str, which converts any non-serializable object to its string representation:

import json
from datetime import datetime

data = {"event": "login", "timestamp": datetime.now()}

result = json.dumps(data, default=str)
print(result)

Output:

{"event": "login", "timestamp": "2026-02-18 21:44:53.790198"}

Custom Encoder for More Control

For more precise control over how specific types are serialized, provide a custom function:

import json
from datetime import datetime

def custom_encoder(obj):
if isinstance(obj, datetime):
return obj.isoformat()
if isinstance(obj, set):
return sorted(list(obj))
raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")

data = {
"event": "login",
"timestamp": datetime.now(),
"tags": {"admin", "active", "verified"}
}

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

Output:

{
"event": "login",
"timestamp": "2026-02-18T21:45:04.199661",
"tags": [
"active",
"admin",
"verified"
]
}

Common Parameters Reference

ParameterPurposeExample
indentPretty print with spacingindent=2
sort_keysAlphabetical key orderingsort_keys=True
separatorsControl whitespace between elementsseparators=(",", ":")
ensure_asciiAllow non-ASCII characters throughensure_ascii=False
defaultHandle non-serializable typesdefault=str

Quick Reference

FunctionInputOutputTypical Use Case
json.dumps()Python objectJSON stringAPI responses, logging, in-memory processing
json.dump()Python objectWritten to fileConfiguration files, data export
json.loads()JSON stringPython objectParsing API responses, processing JSON data
json.load()File objectPython objectReading configuration files, loading saved data

Summary

  • Use json.dumps() when you need a JSON string in memory for API responses, logging, or further processing.
  • Use json.dump() when writing directly to a file for better memory efficiency with large datasets.

Both functions accept the same formatting parameters like indent, sort_keys, and default.

The naming convention is consistent across the entire json module: the "s" suffix means string operations, and its absence means file operations.