datetime.date is not json serializable

717 views
Skip to first unread message

elcaiaimar

unread,
Feb 19, 2016, 3:02:48 AM2/19/16
to Django users
Hello, 

I'm having a problem when I try to convert a python dictionary into a json dictionary (json.dumps(results, ensure_ascii=False)).
Everything is ok, but when there is a date as a valure of the dictionary I get this error: datetime.date is not json serializable. I don't know how to solve this.

Here my code:

mysqldb = get_mysql_db() cursor = mysqldb.cursor()# SQL query
cursor
.execute("SELECT titulo, url from content_medios")
# getting the name of columns
columns
= [column[0] for column in cursor.description]
 
# creating the dictionary
results
= []
for row in cursor.fetchall():
 results
.append(dict(zip(columns, row)))

# converting from py to json
jsonarray
= json.dumps(results, ensure_ascii=False)
return jsonarray

mysqldb
.close()





Thank you in advance

Tim Graham

unread,
Feb 19, 2016, 9:59:24 AM2/19/16
to Django users
datetime isn't JSON serializable by default. Django includes a custom encoder which handles datetime and some other types. You can use it like this:

from django.core.serializers.json import DjangoJSONEncoder
data =  json.dumps(data, cls=DjangoJSONEncoder)
Reply all
Reply to author
Forward
0 new messages