Writing JSON data to files is a common task in Python. Whether you're saving API responses, creating configuration files, or exporting data, Python's json.dump() function makes it easy. You can also use our JSON to Python converter to generate Python code from JSON data.
This comprehensive guide covers everything you need to know about writing JSON to files in Python, from basic examples to advanced techniques with formatting, encoding, and error handling. For reading JSON files, check our Python JSON Parser guide.
Quick Reference: Learn more about Python JSON basics or explore advanced file I/O techniques.
Basic: Write JSON to File with json.dump()
The json.dump() function writes Python data (dictionaries, lists) directly to a file. Read more in the official Python documentation.
Simple Example
import json
# Python dictionary
server_config = {
"hostname": "api-server-01",
"port": 8080,
"ssl_enabled": True,
"max_connections": 100
}
# Write to JSON file
with open('server_config.json', 'w') as file:
json.dump(server_config, file)
print("JSON file created successfully!")This creates a file called server_config.json with your data.
Pretty Printing: Formatting JSON Output
By default, json.dump() writes compact JSON. Use the indent parameter to create human-readable, formatted JSON files. Learn more about JSON formatting best practices.
Without Indent (Compact)
import json
data = {"name": "Alice", "age": 30, "city": "New York"}
with open('compact.json', 'w') as file:
json.dump(data, file)
# Output file content: {"name": "Alice", "age": 30, "city": "New York"}With Indent (Readable)
import json
data = {
"name": "Alice",
"age": 30,
"city": "New York",
"skills": ["Python", "JavaScript", "SQL"]
}
# Write with 4-space indentation
with open('formatted.json', 'w') as file:
json.dump(data, file, indent=4)
print("Formatted JSON file created!")Output file will be beautifully formatted and easy to read!
Result in formatted.json:
{
"name": "Alice",
"age": 30,
"city": "New York",
"skills": [
"Python",
"JavaScript",
"SQL"
]
}Writing JSON with International Characters
When writing JSON with international characters (Chinese, Arabic, emoji, etc.), use UTF-8 encoding and set ensure_ascii=False.
Default Behavior (ASCII Escaped)
import json
data = {
"name": "用户",
"city": "São Paulo",
"message": "Hello 👋"
}
# Default: ASCII-escaped
with open('ascii.json', 'w') as file:
json.dump(data, file, indent=2)
# Output: {"name": "\u7528\u6237", "city": "S\u00e3o Paulo", ...}Characters are escaped with \\uXXXX format.
Preserve Unicode Characters
import json
data = {
"name": "用户",
"city": "São Paulo",
"country": "Brasil",
"message": "Hello 👋 مرحبا"
}
# Write with UTF-8 encoding and preserve Unicode
with open('unicode.json', 'w', encoding='utf-8') as file:
json.dump(data, file, indent=2, ensure_ascii=False)
print("Unicode JSON file created!")Characters remain readable in the file!
Sorting JSON Keys
Use sort_keys=True to write JSON with alphabetically sorted keys. This is useful for version control and comparing JSON files.
import json
data = {
"port": 8080,
"hostname": "server-01",
"ssl": True,
"api_key": "abc123"
}
# Write with sorted keys
with open('sorted.json', 'w') as file:
json.dump(data, file, indent=2, sort_keys=True)
# Output:
# {
# "api_key": "abc123",
# "hostname": "server-01",
# "port": 8080,
# "ssl": true
# }Error Handling When Writing JSON
Always handle potential errors when writing files. Use try-except blocks to catch common issues.
Complete Error Handling Example
import json
data = {
"server": "api-01",
"port": 8080,
"endpoints": ["/api/users", "/api/products"]
}
try:
with open('config.json', 'w') as file:
json.dump(data, file, indent=2)
print("✓ JSON file written successfully!")
except IOError as e:
print(f"Error writing file: {e}")
except TypeError as e:
print(f"Error: Data contains non-serializable types: {e}")
except Exception as e:
print(f"Unexpected error: {e}")Handling Non-Serializable Objects
import json
from datetime import datetime
data = {
"event": "User Login",
"timestamp": datetime.now(), # This will cause an error!
"user_id": 12345
}
try:
with open('event.json', 'w') as file:
json.dump(data, file)
except TypeError as e:
print(f"Error: {e}")
# Output: Object of type datetime is not JSON serializable
# Solution: Convert datetime to string
data["timestamp"] = datetime.now().isoformat()
with open('event.json', 'w') as file:
json.dump(data, file, indent=2)
print("Fixed! JSON file created successfully!")Real-World Examples
Example 1: Saving API Response
import json
import requests
# Fetch data from API
response = requests.get('https://api.example.com/users')
data = response.json()
# Save to file
with open('users_backup.json', 'w') as file:
json.dump(data, file, indent=2)
print(f"Saved {len(data)} users to file!")Example 2: Creating Configuration File
import json
# Application configuration
config = {
"database": {
"host": "localhost",
"port": 5432,
"name": "myapp_db",
"user": "admin"
},
"logging": {
"level": "INFO",
"file": "/var/log/app.log"
},
"features": {
"enable_cache": True,
"max_retries": 3,
"timeout": 30
}
}
# Save config
with open('app_config.json', 'w') as file:
json.dump(config, file, indent=4)
print("Configuration file created!")Example 3: Exporting Data from Database
import json
import sqlite3
# Connect to database
conn = sqlite3.connect('myapp.db')
cursor = conn.cursor()
# Fetch data
cursor.execute('SELECT id, name, email FROM users')
rows = cursor.fetchall()
# Convert to list of dictionaries
users = [
{"id": row[0], "name": row[1], "email": row[2]}
for row in rows
]
# Save to JSON file
with open('users_export.json', 'w') as file:
json.dump(users, file, indent=2)
conn.close()
print(f"Exported {len(users)} users to JSON!")Example 4: Updating Existing JSON File
import json
# Read existing JSON file
with open('settings.json', 'r') as file:
settings = json.load(file)
# Update settings
settings['last_updated'] = "2025-01-16"
settings['version'] = "2.1.0"
settings['new_feature'] = True
# Write updated data back to file
with open('settings.json', 'w') as file:
json.dump(settings, file, indent=2)
print("Settings updated successfully!")json.dump() vs json.dumps() - What's the Difference?
Understanding the difference between these two functions is crucial:
| Function | Output | Use Case |
|---|---|---|
| json.dump() | Writes to file | Saving data to disk |
| json.dumps() | Returns string | Sending over network, logging |
Side-by-Side Comparison
import json
data = {"name": "Bob", "age": 25}
# json.dump() - Write to FILE
with open('data.json', 'w') as file:
json.dump(data, file) # No return value
# json.dumps() - Convert to STRING
json_string = json.dumps(data) # Returns string
print(json_string) # {"name": "Bob", "age": 25}
# You can also manually write the string to a file
with open('data2.json', 'w') as file:
file.write(json.dumps(data, indent=2))Best Practices for Writing JSON Files
with open() to ensure files are properly closedindent=2 or indent=4 for human-readable filesencoding='utf-8' and ensure_ascii=False for international textsort_keys=True for version-controlled configsExternal Resources for Python JSON
Summary
Writing JSON to files in Python is straightforward with json.dump(). Remember these key points:
- •Use
json.dump(data, file)to write to files - •Add
indent=4for readable formatting - •Use
encoding='utf-8'andensure_ascii=Falsefor Unicode - •Always wrap in try-except blocks for error handling
- •Convert non-serializable objects (datetime, sets) before writing
Next Steps: Learn how to read and parse JSON files in Python or explore more JSON examples at PYnative.