JSON Serialization of Datetime Objects
When attempting to convert a Python dictionary containing datetime objects to JSON using the jsonify() function, you may encounter the error "datetime.datetime not JSON serializable." This error occurs because JSON does not natively support datetime objects.
To resolve this issue and successfully serialize your dictionary, you can utilize the default parameter of the json.dumps() function, as demonstrated in the following example:
import json sample = {} sample['title'] = "String" sample['somedate'] = datetime(2012, 8, 8, 21, 46, 24, 862000) # Convert the dictionary to JSON while handling datetime objects json_data = json.dumps(sample, indent=4, sort_keys=True, default=str)
The default=str argument ensures that objects that are not inherently JSON serializable, such as datetime objects, are converted to strings. This allows the JSON serialization process to proceed successfully, resulting in a JSON string that you can further use or manipulate.
The above is the detailed content of How to Serialize Python datetime Objects in JSON?. For more information, please follow other related articles on the PHP Chinese website!