Problem
My basic dict is as follows:
sample = {}
sample['title'] = "String"
sample['somedate'] = somedatetimehere
When I use jsonify(sample), I get the following:
TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
What can I do to ensure that the inaccuracy in my dictionary sample is corrected?
Note: The dictionaries are formed by the retrieval of records from mongodb, and when I print str(sample[‘somedate’]), the output is 2012-08-08 21:46:24.862000, which may or may not be meaningful.
Asked by Rolando
Solution #1
My sloppy JSON dump, which consumes dates and everything:
json.dumps(my_dictionary, indent=4, sort_keys=True, default=str)
Answered by jjmontes
Solution #2
A basic approach based on a special serializer that just translates datetime, based on previous replies. datetime and datetime are two terms that can be used interchangeably. converting date objects to strings
from datetime import date, datetime
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime, date)):
return obj.isoformat()
raise TypeError ("Type %s not serializable" % type(obj))
As can be seen, the code simply checks to see if the object is of the datetime.datetime or datetime.datetime classes, and then uses.isoformat() to serialize it in ISO 8601 format (YYYY-MM-DDTHH:MM:SS) (which is easily decoded by JavaScript). Other code could be used instead of str() if more elaborate serialized representations are desired (see other answers to this question for examples). To cope with the circumstance where it is called with a non-serializable type, the code raises an exception.
The following is an example of how to use the json serial function:
from datetime import datetime
from json import dumps
print dumps(datetime.now(), default=json_serial)
The json module documentation’s Section Basic Usage has more information on how the default option to json.dumps works.
Answered by jgbarah
Solution #3
The initial response took into account the way MongoDB’s “date” fields were represented:
{“$date”: 1506816000000}
Check out @jjmontes’ answer for a simple solution that doesn’t require any dependencies if you want a generic Python solution for serializing datetime to json.
Because you’re using mongoengine (as suggested in the comments), and pymongo is a dependency, pymongo includes built-in json serialization utilities: http://api.mongodb.org/python/1.10.1/api/bson/json util.html
Example usage (serialization):
from bson import json_util
import json
json.dumps(anObject, default=json_util.default)
Example usage (deserialization):
json.loads(aJsonString, object_hook=json_util.object_hook)
Django comes with a native DjangoJSONEncoder serializer that takes care of this.
See https://docs.djangoproject.com/en/dev/topics/serialization/#djangojsonencoder
from django.core.serializers.json import DjangoJSONEncoder
return json.dumps(
item,
sort_keys=True,
indent=1,
cls=DjangoJSONEncoder
)
One distinction I’ve found between DjangoJSONEncoder and a custom default such as this:
import datetime
import json
def default(o):
if isinstance(o, (datetime.date, datetime.datetime)):
return o.isoformat()
return json.dumps(
item,
sort_keys=True,
indent=1,
default=default
)
Is that Django removes a small portion of the data:
"last_login": "2018-08-03T10:51:42.990", # DjangoJSONEncoder
"last_login": "2018-08-03T10:51:42.990239", # default
As a result, in some circumstances, you may need to be cautious.
Answered by jdi
Solution #4
I recently ran into this issue, and my answer was to subclass json. JSONEncoder:
from datetime import datetime
import json
class DateTimeEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, datetime):
return o.isoformat()
return json.JSONEncoder.default(self, o)
Do something like this in your call: json.dumps(yourobj, cls=DateTimeEncoder) I obtained the.isoformat() from one of the previous responses.
Answered by lenny
Solution #5
Make a string out of the date.
sample['somedate'] = str( datetime.utcnow() )
Answered by D.A
Post is based on https://stackoverflow.com/questions/11875770/how-to-overcome-datetime-datetime-not-json-serializable