Home > Backend Development > Python Tutorial > 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
Release: 2024-10-20 19:14:02
Original
945 people have browsed it

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

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

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!

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