API Navigator Logo

Python `json.dump()` vs `json.dumps()`

Author: Newtum

This guide clarifies the difference between `json.dump()` and `json.dumps()` in Python's `json` module, which are used for serializing Python objects to the JSON format.

`json.dumps()`: Dump to a String

The `dumps()` function (with an 's' for 'string') serializes a Python object into a JSON-formatted **string**. This is useful when you want to send JSON data over a network or store it in a text-based field.

import json

data = {'name': 'Frank', 'city': 'Chicago'}

# Serializes the dictionary to a string variable
json_string = json.dumps(data, indent=2)

print("Type of output:", type(json_string))
print("JSON String:")
print(json_string)

`json.dump()`: Dump to a File

The `dump()` function (no 's') writes the JSON-formatted data directly to a **file-like object** (like a file opened in write mode). This is more memory-efficient for writing large data structures to disk.

import json
from io import StringIO

data = {'name': 'Grace', 'city': 'Houston'}

# In a real scenario, you would open a file:
# with open('data.json', 'w') as f:
#     json.dump(data, f, indent=2)

# Here, we simulate a file with StringIO
string_io_file = StringIO()
json.dump(data, string_io_file, indent=2)

# Get the content written to the 'file'
file_content = string_io_file.getvalue()

print("Content written to file-like object:")
print(file_content)