Home >Web Front-end >JS Tutorial >How to Handle Datetime Objects in JSON Conversions Between Python and JavaScript?
When transferring data between Python and JavaScript using JSON, particular attention should be given to handling datetime objects. This article explores the optimal approach for serializing datetime objects in Python and deserializing them in JavaScript.
Utilize the default parameter in Python's json.dumps function to handle datetime serialization:
<code class="python">date_handler = lambda obj: ( obj.isoformat() if isinstance(obj, (datetime.datetime, datetime.date)) else None ) json.dumps(datetime.datetime.now(), default=date_handler) # Output: '"2010-04-20T20:08:21.634121"' (ISO 8601 format)</code>
In JavaScript, use the JSON.parse function and handle deserialization with a custom reviver function:
<code class="javascript">let date = JSON.parse(jsonString, (key, value) => { if (typeof value === 'string' && value.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/)) { return new Date(value); } return value; });</code>
A more inclusive default handler function can be defined to accommodate various data types:
<code class="python">import datetime def handler(obj): if hasattr(obj, 'isoformat'): return obj.isoformat() elif isinstance(obj, datetime.date): return str(obj) # Convert to string for date objects elif isinstance(obj, ...): return ... # Handle other types as needed else: raise TypeError('Cannot serialize object of type {} with value {}'.format(type(obj), repr(obj)))</code>
The improved handler includes:
The above is the detailed content of How to Handle Datetime Objects in JSON Conversions Between Python and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!