Handling Datetime Objects in JSON Between Python and JavaScript
When exchanging data between Python and JavaScript, it's common to encounter datetime objects. To ensure seamless serialization and deserialization of these objects, various approaches can be employed.
One recommended method involves utilizing the 'default' parameter of json.dumps in Python to handle datetime objects. This parameter enables the specification of a handler function that converts the datetime objects into a serializable format.
from datetime import datetime
date_handler = lambda obj: (
obj.isoformat()
if isinstance(obj, (datetime.datetime, datetime.date))
else None
)
json_str = json.dumps(datetime.datetime.now(), default=date_handler)
print(json_str)
This approach ensures that Python datetime objects are converted to ISO 8601 format, which is standardized and recognized by JavaScript.
"2010-04-20T20:08:21.634121"
Alternatively, a more comprehensive default handler function can be defined to handle various object types:
def handler(obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
elif isinstance(obj, ...):
return ...
else:
raise TypeError, 'Object of type %s with value of %s is not JSON serializable' % (type(obj), repr(obj))
This function checks for the presence of an 'isoformat' attribute, which is common in datetime objects, and converts it to a serializable format. Additionally, it handles other object types as needed.
By leveraging these techniques, datetime objects can be efficiently serialized from Python and deserialized in JavaScript, facilitating smooth data exchange between the two languages.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3