To write JSON data to a file in Python, you can use the built-in json
module. Below is a detailed guide with multiple examples, covering different scenarios and configurations.
Basic Usage
1. Writing a Dictionary to a JSON File
import json
data = {
"name": "Alice",
"age": 30,
"is_student": False,
"courses": ["Math", "Physics"]
}
# Write to a file
with open("data.json", "w", encoding="utf-8") as file:
json.dump(data, file)
Output (data.json
):
{"name": "Alice", "age": 30, "is_student": false, "courses": ["Math", "Physics"]}
Formatting Options
2. Pretty-Print JSON (Indentation)
with open("data_pretty.json", "w", encoding="utf-8") as file:
json.dump(data, file, indent=4) # 4-space indentation
Output:
{
"name": "Alice",
"age": 30,
"is_student": false,
"courses": [
"Math",
"Physics"
]
}
3. Sort Keys Alphabetically
with open("data_sorted.json", "w", encoding="utf-8") as file:
json.dump(data, file, indent=4, sort_keys=True)
Output:
{
"age": 30,
"courses": [
"Math",
"Physics"
],
"is_student": false,
"name": "Alice"
}
Handling Special Characters
4. Preserve Non-ASCII Characters (e.g., Emojis)
data = {"message": "Hello! 👋"}
with open("unicode_data.json", "w", encoding="utf-8") as file:
json.dump(data, file, ensure_ascii=False, indent=4)
Output:
{
"message": "Hello! 👋"
}
Advanced Use Cases
5. Writing a List of Dictionaries
users = [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"},
{"id": 3, "name": "Charlie"}
]
with open("users.json", "w", encoding="utf-8") as file:
json.dump(users, file, indent=4)
Output:
[
{
"id": 1,
"name": "Alice"
},
{
"id": 2,
"name": "Bob"
},
{
"id": 3,
"name": "Charlie"
}
]
6. Appending Data to an Existing JSON File
Note: JSON files are not designed for appending. Instead, read the file, update the data, and rewrite it:
# Step 1: Read existing data
with open("users.json", "r", encoding="utf-8") as file:
existing_data = json.load(file)
# Step 2: Append new data
new_user = {"id": 4, "name": "Diana"}
existing_data.append(new_user)
# Step 3: Write back to the file
with open("users.json", "w", encoding="utf-8") as file:
json.dump(existing_data, file, indent=4)
Handling Non-Serializable Objects
7. Custom JSON Encoder for Objects (e.g., datetime
)
If your data includes non-serializable objects (like datetime
), create a custom encoder:
from datetime import datetime
import json
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat() # Convert datetime to ISO string
return super().default(obj)
data = {
"event": "Conference",
"date": datetime(2023, 10, 15)
}
with open("event.json", "w", encoding="utf-8") as file:
json.dump(data, file, cls=CustomEncoder, indent=4)
Output:
{
"event": "Conference",
"date": "2023-10-15T00:00:00"
}
Key Parameters for json.dump()
Parameter | Description |
---|---|
indent | Number of spaces for indentation (e.g., 4 ). |
sort_keys | Sort dictionary keys alphabetically (True /False ). |
ensure_ascii | Escape non-ASCII characters if True (default). Set to False to preserve Unicode. |
cls | Custom JSON encoder class (for non-serializable objects). |
Common Errors & Fixes
TypeError: Object of type X is not JSON serializable
- Cause: Trying to serialize unsupported types (e.g.,
datetime
, custom classes). - Fix: Use a custom encoder or convert the object to a string first.
- File Permission Errors
- Ensure the file is not open in another program.
- Incorrect File Mode
- Use
"w"
(write) mode, not"r"
(read) or"a"
(append).
Best Practices
- Always use the
with
statement to ensure proper file handling. - Specify
encoding="utf-8"
to handle international characters. - Validate JSON output using tools like JSONLint.
By following these examples, you can handle most JSON writing tasks in Python!