Of course! Writing data to a JSON file in Python is a common task, and the built-in json module makes it straightforward.

Here's a complete guide, from the basic method to more advanced and robust techniques.
The Basic Method: json.dump()
The primary function for writing Python objects to a JSON file is json.dump().
Key Function: json.dump(obj, file, indent=None, ...)
obj: The Python object (like a dictionary, list, string, etc.) you want to write.file: A file object opened in write mode ('w').indent(optional): An integer to specify the indentation level for pretty-printing the JSON.
Step-by-Step Example
Let's create a Python dictionary and save it to a file named data.json.

Step 1: Import the json module
import json
Step 2: Prepare your Python data
This can be any JSON-serializable object (dict, list, str, int, bool, None).
data = {
"name": "John Doe",
"age": 30,
"isStudent": False,
"courses": [
{"title": "History", "credits": 3},
{"title": "Math", "credits": 4}
],
"address": None
}
Step 3: Open the file in write mode ('w')
It's crucial to open the file with 'w' (write mode). If the file doesn't exist, it will be created. If it does exist, its contents will be overwritten.
The with statement is the recommended way to handle files, as it automatically closes the file for you.
with open('data.json', 'w') as json_file:
pass # We will write to the file in the next step
Step 4: Use json.dump() to write the data
Now, combine everything. We'll add the indent=4 argument to make the output human-readable.
import json
data = {
"name": "John Doe",
"age": 30,
"isStudent": False,
"courses": [
{"title": "History", "credits": 3},
{"title": "Math", "credits": 4}
],
"address": None
}
# Open the file in write mode ('w')
with open('data.json', 'w') as json_file:
# Use json.dump to write the data to the file
# indent=4 makes the JSON file nicely formatted
json.dump(data, json_file, indent=4)
After running this code, a file named data.json will be created in the same directory with the following content:
{
"name": "John Doe",
"age": 30,
"isStudent": false,
"courses": [
{
"title": "History",
"credits": 3
},
{
"title": "Math",
"credits": 4
}
],
"address": null
}
Alternative: Writing to a String (json.dumps())
Sometimes you don't need to write to a file right away; you might want to get the JSON as a string first. For this, you use json.dumps() (dump string).
Key Function: json.dumps(obj, indent=None, ...)
This is useful for sending JSON data over a network or storing it in a database.
import json
data = {
"name": "Jane Doe",
"id": 123,
"active": True
}
# Get the JSON as a string
json_string = json.dumps(data, indent=4)
print(json_string)
# You can now use this string as needed
# For example, save it to a file manually:
# with open('data_string.json', 'w') as f:
# f.write(json_string)
Handling Special Cases
A. Writing to a Specific Path (e.g., a data folder)
If you want to save the file in a subdirectory, make sure that directory exists first, or Python will raise a FileNotFoundError. The os module can help with this.
import json
import os
data = {"message": "This is in a subfolder."}
# Define the directory and file path
dir_name = 'data'
file_name = 'message.json'
file_path = os.path.join(dir_name, file_name)
# Create the directory if it doesn't exist
os.makedirs(dir_name, exist_ok=True)
with open(file_path, 'w') as json_file:
json.dump(data, json_file, indent=4)
print(f"File saved to {file_path}")
B. Handling Non-JSON-Serializable Objects
What if your data contains a Python object that json doesn't know how to handle, like a datetime object?
import json
from datetime import datetime
data = {
"event": "Product Launch",
"timestamp": datetime.now() # This will cause a TypeError
}
# This will raise a TypeError: Object of type datetime is not JSON serializable
# with open('error.json', 'w') as f:
# json.dump(data, f)
Solution: Create a Custom Encoder
You can create a custom class that inherits from json.JSONEncoder and override its default method to handle specific types.
import json
from datetime import datetime
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
# If the object is a datetime, convert it to an ISO format string
if isinstance(obj, datetime):
return obj.isoformat()
# Let the base class default method raise the TypeError
return super().default(obj)
data = {
"event": "Product Launch",
"timestamp": datetime.now()
}
# Use the cls argument to specify your custom encoder
with open('event.json', 'w') as json_file:
json.dump(data, json_file, indent=4, cls=DateTimeEncoder)
# event.json will look like:
# {
# "event": "Product Launch",
# "timestamp": "2025-10-27T10:30:00.123456"
# }
Summary: json.dump() vs. json.dumps()
| Function | Purpose | Returns | Example Use Case |
|---|---|---|---|
json.dump() |
Writes a Python object directly to a file object. | None |
Saving configuration data, program state, or API responses to a file on disk. |
json.dumps() |
Serializes a Python object into a JSON formatted string. | str |
Preparing data to be sent as an HTTP request body, storing in a text field in a database, or printing for debugging. |
