Handling Datetime Objects in JSON Exchange Between Python and JavaScript
When exchanging datetime objects between Python and JavaScript using JSON, there exists a challenge due to the different ways the two languages represent dates and times. This article presents the best practice for this task.
Python-to-JavaScript Conversion
To serialize a datetime.datetime object in Python for JSON transmission, use the 'default' parameter of the json.dumps function with a custom date handler function:
1 2 3 4 5 6 |
|
This function returns the ISO 8601 format of the datetime object, which is a widely accepted standard for date and time representation.
JavaScript-to-Python Conversion
In JavaScript, you can deserialize the received JSON string with a custom date reviver function. This function will parse the ISO 8601 string and reconstruct the datetime object:
1 2 |
|
Comprehensive Date Handler
For a more comprehensive approach, you can create a custom date handler function that covers multiple data types:
1 2 3 4 5 6 7 |
|
This function ensures that different types of objects are handled appropriately during serialization.
Additional Notes
The above is the detailed content of How to Handle Datetime Objects in JSON Exchange Between Python and JavaScript. For more information, please follow other related articles on the PHP Chinese website!