Home >Web Front-end >JS Tutorial >How to Serialize and Deserialize JSON Datetimes between Python and JavaScript?
Serializing and Deserializing JSON Datetime between Python and JavaScript
In web development, transmitting data between different systems is crucial. One common challenge arises when dealing with Python's datetime.datetime objects in a context where JSON is used as the data exchange format, particularly in scenarios involving communication with JavaScript.
To tackle this challenge effectively, you can leverage the default parameter of the json.dumps function. By defining a custom date_handler function and passing it as the default argument, you can control how datetime objects are serialized into a form that JavaScript can interpret.
Here's a sample implementation of the date_handler function:
<code class="python">date_handler = lambda obj: ( obj.isoformat() if isinstance(obj, (datetime.datetime, datetime.date)) else None )</code>
This function checks if the object is an instance of datetime.datetime or datetime.date, and if so, it returns the object's ISO 8601 formatted string representation. This format is compatible with JavaScript's native Date object.
In JavaScript, you can parse the received JSON string containing the serialized date using the JSON.parse function, and the Date object can be created from the parsed date string.
However, to handle a wider range of complex data types, you might need a more comprehensive default handler function like the one below:
<code class="python">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))</code>
This enhanced handler will not only check for datetime objects but also handle other data types as needed.
Remember, when sending datetime objects to JavaScript, they are serialized to strings. JavaScript then reconstructs Date objects based on these strings. The ISO 8601 format ensures compatibility and allows for convenient and reliable data exchange between Python and JavaScript.
The above is the detailed content of How to Serialize and Deserialize JSON Datetimes between Python and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!