10 Examples to Learn the JSON module of Python | by Soner Yıldırım | May, 2023
Example 7: The default parameter
The default
parameter of the dumps
function can be used for serializing complex Python objects, which otherwise can’t be serialized.
For instance, the following code raises a TypeError
because of the datetime
object:
import jsondata = {
"name": "John Doe",
"age": 28,
"city": "Houston",
"birthday": datetime.datetime.now()
}
json_data = json.dumps(data, indent=4)
# output
TypeError: Object of type datetime is not JSON serializable
To handle this error, we can write a custom function that tells the dumps
function how to serialize this object:
import json
import datetimedef datetime_serializer(x):
if isinstance(x, datetime.datetime):
return x.isoformat()
data = {
"name": "John Doe",
"age": 28,
"city": "Houston",
"birthday": datetime.datetime.now()
}
json_data = json.dumps(data, indent=4, default=datetime_serializer)
print(json_data)
# output
{
"name": "John Doe",
"age": 28,
"city": "Houston",
"birthday": "2023-05-14T07:22:53.917531"
}
Example 7: The default parameter
The default
parameter of the dumps
function can be used for serializing complex Python objects, which otherwise can’t be serialized.
For instance, the following code raises a TypeError
because of the datetime
object:
import jsondata = {
"name": "John Doe",
"age": 28,
"city": "Houston",
"birthday": datetime.datetime.now()
}
json_data = json.dumps(data, indent=4)
# output
TypeError: Object of type datetime is not JSON serializable
To handle this error, we can write a custom function that tells the dumps
function how to serialize this object:
import json
import datetimedef datetime_serializer(x):
if isinstance(x, datetime.datetime):
return x.isoformat()
data = {
"name": "John Doe",
"age": 28,
"city": "Houston",
"birthday": datetime.datetime.now()
}
json_data = json.dumps(data, indent=4, default=datetime_serializer)
print(json_data)
# output
{
"name": "John Doe",
"age": 28,
"city": "Houston",
"birthday": "2023-05-14T07:22:53.917531"
}