How to Fix “datetime is not JSON serializable” TypeError in Python [All Method]️
![How to Fix “datetime is not JSON serializable” TypeError in Python [All Method]️](https://howisguide.com/wp-content/uploads/2022/02/How-to-Fix-datetime-is-not-JSON-serializable-TypeError-in-Python-All-Method.png)
The blog will help about How to Fix “datetime is not JSON serializable” TypeError in Python & learn how to solve different problems that come from coding errors. Error found! Why this could be happening? know and Learn everything.
Question: What is the best solution for this problem? Answer: This blog code can help you solve errors How to Fix “datetime is not JSON serializable” TypeError in Python. Question: What are the reasons for this code mistake and how can it be fixed? Answer: You can find a solution by following the advice in this blog.
Serializing a Python data structure as JSON is quite simple using json.dumps()
.
import json
d = {
'dog': 'corgi'
}
print(json.dumps(d))
# {"dog": "corgi"}
Issue with datetime
Serialization
However, what if we try to serialize a datetime
object?
import json
import datetime
d = {
'dog': 'corgi',
'date': datetime.datetime.now()
}
print(json.dumps(d))
# TypeError: datetime.datetime(2020, 19, 8, 9, 1, 1, 100000) is not JSON serializable
Solution
We can use the default
parameter in json.dumps()
that will be called whenever it doesn’t know how to convert a value, like a datetime
object.
We can write a converter function that stringifies our datetime
object.
def defaultconverter(o):
if isinstance(o, datetime.datetime):
return o.__str__()
Any object that requires special conversions can be added inside if
statements in our defaultconverter
method.
We can then pass this function into that default
parameter.
import json
import datetime
d = {
'dog': 'corgi',
'date': datetime.datetime.now()
}
print(json.dumps(d, default = defaultconverter))
# {"date": "2020-19-08 09:01:01.100000", "dog": "corgi"}
Now you learned, How you can use & How to Fix “datetime is not JSON serializable” TypeError in Python.
If you need help at any point, please send me a message and I will do my best to assist you.