Home >Backend Development >Python Tutorial >How Do I Solve JSON Serialization Errors with Python's datetime Objects?
Overcoming JSON Serialization Issues with datetime.datetime
In the course of working with Python dictionaries containing datetime objects, such as sample['somedate'], you may encounter the following error when attempting to serialize the dictionary to JSON:
TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
The primary solution to this issue lies in providing a custom serialization function to handle datetime objects. A popular approach involves using the default parameter of the json.dumps() function, which accepts a function that takes an object as an input and returns a serializable representation.
In this scenario, a simple implementation could be as follows:
def default(obj): if isinstance(obj, datetime.datetime): return str(obj) # Other logic to handle other types (if needed) json_string = json.dumps(sample, default=default)
This function converts the datetime object to a string representation before serialization. Alternatively, you could utilize Python's built-in ctime() method:
sample['somedate'] = sample['somedate'].ctime() json_string = json.dumps(sample)
This approach converts the datetime object to a human-readable string that can be serialized as part of your dictionary.
The above is the detailed content of How Do I Solve JSON Serialization Errors with Python's datetime Objects?. For more information, please follow other related articles on the PHP Chinese website!