PreservingDatetime Continuity Between Python and JavaScript via JSON
Before venturing into the solution, let's first understand the problem. We have a datetime.datetime object in Python that needs to be serialized and sent to JavaScript through JSON. Upon arrival, JavaScript must be able to deserialize it back into a datetime object without any distortions.
To address this conundrum, JSON's versatile 'default' parameter in json.dumps provides a solution. This parameter enables us to define a custom serialization handler for ourdatetime objects.
The following handler neatly handles the serialization process:
<code class="python">date_handler = lambda obj: ( obj.isoformat() if isinstance(obj, (datetime.datetime, datetime.date)) else None )</code>
When applied, this handler converts datetime objects into ISO 8601 format during serialization:
<code class="python">json.dumps(datetime.datetime.now(), default=date_handler) '"2010-04-20T20:08:21.634121"'</code>
For more complex scenarios, a comprehensive handler is recommended:
<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 handler also generates an improved error message with the object's type and value for better debugging. The inclusion of a date type ensures that dates are also handled gracefully.
The above is the detailed content of How to Preserve Datetime Continuity Between Python and JavaScript via JSON?. For more information, please follow other related articles on the PHP Chinese website!