Home  >  Article  >  Backend Development  >  How to Serialize Python Datetime Objects into JSON for JavaScript De-Serialization?

How to Serialize Python Datetime Objects into JSON for JavaScript De-Serialization?

DDD
DDDOriginal
2024-10-20 19:14:02832browse

How to Serialize Python Datetime Objects into JSON for JavaScript De-Serialization?

Serializing Python Datetime Objects into JSON for JavaScript Applications

When communicating between Python and JavaScript applications using JSON, handling datetime objects can be challenging. This article explores the optimal approach for serializing Python datetime objects into JSON for seamless de-serialization in JavaScript.

To effectively handle datetime objects in JSON, the 'default' parameter in json.dumps() can be utilized. A custom date handler function can be supplied to handle datetime objects during the serialization process.

<code class="python">import datetime

# Create a date handler
date_handler = lambda obj: (
    obj.isoformat()
    if isinstance(obj, (datetime.datetime, datetime.date))
    else None
)

# Serialize a datetime object
json_string = json.dumps(datetime.datetime.now(), default=date_handler)

print(json_string)  # Output: '"2023-02-13T18:38:48.942613"'</code>

The serialization process converts the datetime object into its ISO 8601 representation, which is a string representation widely supported in JavaScript applications.

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()  # Handle datetime objects
    elif isinstance(obj, ...):
        ...                          # Handle other custom object types
    else:
        raise TypeError(f'Object of type {type(obj)} with value {repr(obj)} is not JSON serializable')</code>

This enhanced handler provides additional flexibility in handling different object types during serialization.

The above is the detailed content of How to Serialize Python Datetime Objects into JSON for JavaScript De-Serialization?. 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