1. Problem description
When using python’s own json to convert data to json data, the data in datetime format reports an error: TypeError: Object of type’datetime’ is not JSON serializable
2. Solution
It is to rewrite and construct the json class, when encountering special date processing, the rest will be built-in.
from datetime import date, datetime
class ComplexEncoder(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, json.dumps needs to call the class defined above, specify the cls parameter as ComplexEncoder, the code is as follows:
json.dumps(your_data, cls=ComplexEncoder)
3. Summary
As long as there is an error message about datetime xx is not JSON serializable at runtime, you can use the above methods to solve it perfectly.
Similar Posts:
- [Solved] Python Error: datetime.datetime is not JSON serializable
- 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
- 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
- [Solved] TypeError: string indices must be integers, not str
- Warning: The serializable class * does not declare a static final serialVersionUID