How to Safely Serialize and Deserialize Datetime Objects in JSON between Python and JavaScript?

Mary-Kate Olsen
Release: 2024-10-20 19:12:02
Original
401 people have browsed it

How to Safely Serialize and Deserialize Datetime Objects in JSON between Python and JavaScript?

Serializing and Deserializing Datetime Objects between Python and JavaScript with JSON

When working with JSON, you may encounter the need to transfer datetime objects between Python and JavaScript. Serializing such objects can be tricky. This article explores the best practices for handling datetime objects in JSON communication.

Serialization in Python

To serialize a datetime.datetime object in Python, we can use the json.dumps function with the default parameter. This parameter allows us to specify a custom handler to convert the datetime object into a JSON-serializable format.

<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"'</code>
Copy after login

The isoformat() method of the datetime object returns a string representation in ISO 8601 format, which is universally recognized.

Deserialization in JavaScript

In JavaScript, you can deserialize the serialized datetime string back into a Date object using the Date.parse() function:

<code class="javascript">const dateString = '"2010-04-20T20:08:21.634121"';
const date = new Date(Date.parse(dateString));
// Output: Thu Apr 20 2010 20:08:21 GMT-0400 (Eastern Daylight Time)</code>
Copy after login

Comprehensive Default Handler

For more complex scenarios, you may need a more comprehensive default handler function:

<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 handler can handle multiple object types and provides more informative error messages. Remember to handle both date and datetime objects as needed.

The above is the detailed content of How to Safely 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!