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

How to Serialize and Deserialize Datetime Objects in JSON Between Python and JavaScript

Linda Hamilton
Release: 2024-10-19 17:28:30
Original
970 people have browsed it

How to Serialize and Deserialize Datetime Objects in JSON Between Python and JavaScript

Handling Datetime Objects in JSON Between Python and JavaScript

When exchanging data between Python and JavaScript, it's common to encounter datetime objects. To ensure seamless serialization and deserialization of these objects, various approaches can be employed.

One recommended method involves utilizing the 'default' parameter of json.dumps in Python to handle datetime objects. This parameter enables the specification of a handler function that converts the datetime objects into a serializable format.

<code class="python">from datetime import datetime

date_handler = lambda obj: (
    obj.isoformat()
    if isinstance(obj, (datetime.datetime, datetime.date))
    else None
)
json_str = json.dumps(datetime.datetime.now(), default=date_handler)
print(json_str)</code>
Copy after login

This approach ensures that Python datetime objects are converted to ISO 8601 format, which is standardized and recognized by JavaScript.

"2010-04-20T20:08:21.634121"
Copy after login

Alternatively, a more comprehensive default handler function can be defined to handle various object types:

<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 function checks for the presence of an 'isoformat' attribute, which is common in datetime objects, and converts it to a serializable format. Additionally, it handles other object types as needed.

By leveraging these techniques, datetime objects can be efficiently serialized from Python and deserialized in JavaScript, facilitating smooth data exchange between the two languages.

The above is the detailed content of How to Serialize and Deserialize Datetime Objects in JSON Between Python and 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
Latest Articles by Author
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!