Last modified: May 28, 2026
Python JSON Encode Guide
JSON is a lightweight data format used to exchange data between systems. Python provides a built-in json module to work with JSON data. Encoding means converting a Python object into a JSON string.
This article covers everything you need to know about Python JSON encode. You will learn how to use json.dumps() and json.dump(). We will also explore handling complex data types and custom objects.
JSON encode is essential for APIs, configuration files, and data storage. Understanding it helps you build robust applications.
What is JSON Encode?
JSON encode converts Python objects into a JSON formatted string. The process is also called serialization. The json module makes this simple and efficient.
Python data types like dictionaries, lists, strings, numbers, booleans, and None can be encoded directly. Other types require custom handling.
The two main functions are json.dumps() and json.dump(). The first returns a string. The second writes directly to a file.
Using json.dumps()
The json.dumps() function converts a Python object to a JSON string. It stands for "dump string".
Here is a basic example:
import json
# Python dictionary
data = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# Encode to JSON string
json_string = json.dumps(data)
print(json_string)
Output:
{"name": "Alice", "age": 30, "city": "New York"}
The result is a valid JSON string. Notice that Python True becomes true and None becomes null.
You can also encode lists and nested structures:
import json
# Nested data
data = {
"users": [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25}
],
"active": True,
"count": None
}
json_string = json.dumps(data)
print(json_string)
Output:
{"users": [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}], "active": true, "count": null}
This shows how Python types map to JSON types.
Using json.dump()
The json.dump() function writes JSON data directly to a file. It is useful for saving data permanently.
Here is an example:
import json
data = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# Write to file
with open("data.json", "w") as file:
json.dump(data, file)
This creates a file named data.json with the JSON content. The file is human-readable and easy to share.
Always use with open() to ensure proper file handling. The file mode must be "w" for writing.
Pretty Printing with Indent
By default, JSON output is compact. Use the indent parameter to make it readable.
import json
data = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# Pretty print with indentation
json_string = json.dumps(data, indent=4)
print(json_string)
Output:
{
"name": "Alice",
"age": 30,
"city": "New York"
}
The indent parameter adds spaces for better formatting. Use indent=2 or indent=4 as needed.
Sorting Keys
You can sort the keys alphabetically using the sort_keys parameter.
import json
data = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# Sort keys alphabetically
json_string = json.dumps(data, sort_keys=True, indent=4)
print(json_string)
Output:
{
"age": 30,
"city": "New York",
"name": "Alice"
}
This is helpful when you need consistent output order for comparison or debugging.
Handling Special Types
Python has types like datetime, Decimal, and custom objects. The json module cannot encode them directly. You must use a custom encoder.
One approach is to convert the object to a string first:
import json
from datetime import datetime
data = {
"event": "meeting",
"time": datetime.now()
}
# Convert datetime to string before encoding
data["time"] = data["time"].isoformat()
json_string = json.dumps(data, indent=4)
print(json_string)
Output:
{
"event": "meeting",
"time": "2025-03-26T10:30:00.123456"
}
For complex scenarios, create a custom encoder class that inherits from json.JSONEncoder.
Using a Custom Encoder
Define a subclass of json.JSONEncoder and override the default method.
import json
from datetime import datetime
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
# Let the base class handle other types or raise TypeError
return super().default(obj)
data = {
"event": "meeting",
"time": datetime.now()
}
json_string = json.dumps(data, cls=CustomEncoder, indent=4)
print(json_string)
Output:
{
"event": "meeting",
"time": "2025-03-26T10:30:00.123456"
}
This approach is clean and reusable. You can handle multiple custom types in one encoder.
Handling Non-ASCII Characters
By default, json.dumps() escapes non-ASCII characters. Use ensure_ascii=False to keep them as is.
import json
data = {
"name": "José",
"city": "São Paulo"
}
# Keep non-ASCII characters
json_string = json.dumps(data, ensure_ascii=False, indent=4)
print(json_string)
Output:
{
"name": "José",
"city": "São Paulo"
}
This is useful for international applications. Be careful when sharing files with systems that expect ASCII-only JSON.
Encoding with Skipkeys
If your dictionary contains non-string keys, use skipkeys=True to skip them instead of raising an error.
import json
data = {
"name": "Alice",
123: "numeric key",
(1, 2): "tuple key"
}
# Skip non-string keys
json_string = json.dumps(data, skipkeys=True, indent=4)
print(json_string)
Output:
{
"name": "Alice"
}
The numeric and tuple keys are skipped. Use this when you cannot control the input data.
Common Errors and Solutions
The most common error is TypeError: Object of type XYZ is not JSON serializable. This happens when you try to encode an unsupported type.
Solution: Convert the object to a serializable type or use a custom encoder.
Another error is forgetting to open the file in write mode. Always use "w" with json.dump().
Practical Example: Saving and Loading User Data
Here is a complete example that encodes user data to a file and reads it back.
import json
# Sample user data
user = {
"id": 101,
"username": "alice_2025",
"roles": ["admin", "editor"],
"last_login": "2025-03-26T10:00:00"
}
# Encode and save to file
with open("user.json", "w") as f:
json.dump(user, f, indent=4)
print("User data saved successfully.")
Output:
User data saved successfully.
To read it back, use json.load(). This shows the full cycle of encoding and decoding.
Conclusion
Python JSON encode is a fundamental skill for any developer. The json module provides powerful functions like json.dumps() and json.dump() to convert Python objects to JSON format.
You have learned how to handle indentation, sorting, special types, and custom encoders. These techniques make your code robust and professional.
Practice with different data types and explore the json module documentation. Encoding JSON correctly ensures smooth data exchange across platforms.