Home  >  Article  >  Web Front-end  >  How to Serialize and Deserialize Datetime Objects in JSON Between Python and JavaScript

How to Serialize and Deserialize Datetime Objects in JSON Between Python and JavaScript

Linda Hamilton
Linda HamiltonOriginal
2024-10-19 17:28:30971browse

How to Serialize and Deserialize Datetime Objects in JSON Between Python and JavaScript

Handling Datetime Objects in JSON Between Python and JavaScript

When exchanging data between Python and JavaScript, it's common to encounter datetime objects. To ensure seamless serialization and deserialization of these objects, various approaches can be employed.

One recommended method involves utilizing the 'default' parameter of json.dumps in Python to handle datetime objects. This parameter enables the specification of a handler function that converts the datetime objects into a serializable format.

<code class="python">from datetime import datetime

date_handler = lambda obj: (
    obj.isoformat()
    if isinstance(obj, (datetime.datetime, datetime.date))
    else None
)
json_str = json.dumps(datetime.datetime.now(), default=date_handler)
print(json_str)</code>

This approach ensures that Python datetime objects are converted to ISO 8601 format, which is standardized and recognized by JavaScript.

"2010-04-20T20:08:21.634121"

Alternatively, 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()
    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 function checks for the presence of an 'isoformat' attribute, which is common in datetime objects, and converts it to a serializable format. Additionally, it handles other object types as needed.

By leveraging these techniques, datetime objects can be efficiently serialized from Python and deserialized in JavaScript, facilitating smooth data exchange between the two languages.

The above is the detailed content of How to 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