Techno Blender
Digitally Yours.

10 Examples to Learn the JSON module of Python | by Soner Yıldırım | May, 2023

0 43


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 json

data = {
"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 datetime

def 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 json

data = {
"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 datetime

def 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"
}

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! Techno Blender is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – [email protected]. The content will be deleted within 24 hours.

Leave a comment