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

How to Handle Datetime Objects in JSON Conversions Between Python and JavaScript?

Susan Sarandon
Release: 2024-10-19 17:29:30
Original
626 people have browsed it

How to Handle Datetime Objects in JSON Conversions Between Python and JavaScript?

JSON datetime Conversion between Python and JavaScript

When transferring data between Python and JavaScript using JSON, particular attention should be given to handling datetime objects. This article explores the optimal approach for serializing datetime objects in Python and deserializing them in JavaScript.

Serialization in Python

Utilize the default parameter in Python's json.dumps function to handle datetime serialization:

<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"' (ISO 8601 format)</code>
Copy after login

Deserialization in JavaScript

In JavaScript, use the JSON.parse function and handle deserialization with a custom reviver function:

<code class="javascript">let date = JSON.parse(jsonString, (key, value) => {
  if (typeof value === 'string' && value.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/)) {
    return new Date(value);
  }
  return value;
});</code>
Copy after login

Comprehensive Default Handler in Python

A more inclusive default handler function can be defined to accommodate various data types:

<code class="python">import datetime

def handler(obj):
    if hasattr(obj, 'isoformat'):
        return obj.isoformat()
    elif isinstance(obj, datetime.date):
        return str(obj)  # Convert to string for date objects
    elif isinstance(obj, ...):
        return ...  # Handle other types as needed
    else:
        raise TypeError('Cannot serialize object of type {} with value {}'.format(type(obj), repr(obj)))</code>
Copy after login

Improved Default Handler

The improved handler includes:

  • Handling of both datetime and date objects
  • Output of both type and value upon encountering a non-serializable object

The above is the detailed content of How to Handle Datetime Objects in JSON Conversions 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!