Home >Backend Development >Python Tutorial >How to Safely Serialize and Deserialize Datetime Objects in JSON between Python and JavaScript?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-20 19:12:02483browse

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>

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>

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>

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!

Statement:
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