Question:
The project is developed with Django, and the returned data contains a time field. When JSON. Dumps(), it will prompt: datetime. Datetime is not JSON serializable
Solution:
import json
from datetime import date, datetime
class DateEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(obj, date):
return obj.strftime("%Y-%m-%d")
else:
return json.JSONEncoder.default(self, obj)
When using it, return will do
return HttpResponse(json.dumps(rows, cls=DateEncoder))
Similar Posts:
- TypeError: Object of type ‘datetime‘ is not JSON serializable [Solved]
- TypeError: Object of type ‘int32’ is not JSON serializable
- ValueError: day is out of range for month [How to Solve]
- ValueError: day is out of range for month [How to Solve]
- Python TypeError: Object of type int64 is not JSON serializable
- Warning: The serializable class * does not declare a static final serialVersionUID
- Springboot uses the Datetimeformat (pattern = “yyyy MM DD HH: mm: SS”) annotation to automatically convert the string to date type error
- Python JSON error json.decoder.jsondecodeerror Chinese
- Python: json:json.decoder.JSONDecodeError: Invalid control character at: line 2 column 18 (char 19)
- [Solved] java.lang.IllegalArgumentException: Cannot format given Object as a Date