Home > Web Front-end > JS Tutorial > body text

How to Serialize Python Datetime Objects for Seamless JSON Exchange with JavaScript?

DDD
Release: 2024-10-19 17:32:02
Original
630 people have browsed it

How to Serialize Python Datetime Objects for Seamless JSON Exchange with JavaScript?

Serializing Python Datetime Objects for JSON Exchange with JavaScript

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!