Home  >  Article  >  Web Front-end  >  How to Handle Datetime Objects in JSON Conversions Between Python and JavaScript?

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

Susan Sarandon
Susan SarandonOriginal
2024-10-19 17:29:30627browse

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>

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>

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>

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!

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