When using JSON to communicate between Python and JavaScript, challenges arise in handling datetime objects. To address this, Python provides a customizable default handler, which can be integrated with json.dumps to enable proper serialization and deserialization of these objects.
In Python, the following handler function leverages the ISO 8601 format to convert datetime objects into JSON-compliant strings:
<code class="python">date_handler = lambda obj: ( obj.isoformat() if isinstance(obj, (datetime.datetime, datetime.date)) else None )</code>
This ensures that the resulting JSON string is in a format that can be easily parsed by JavaScript.
However, it's important to consider that ISO 8601 format does not convey the type of the object. For more comprehensive handling, a more robust handler function can be defined:
<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 extended handler不仅提供了对日期值的格式化,还明确了对象的类型,使其在 JavaScript 中更易于反序列化。
The above is the detailed content of How to Serialize Python Datetime Objects for Seamless JSON Exchange with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!