Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django JSON custom serializing losing datetime type

I'm encoding data fetched from a Django cursor using Django json libraries, however I'm seeing datetimes after deserializing are now unicode type. Simple example:

import datetime
from django.core.serializers.json import json, DjangoJSONEncoder


today = datetime.datetime.now()
encoded = json.dumps(today, cls=DjangoJSONEncoder)
type(json.loads(encoded))
>> unicode

If I'm not mistaken variable types should be respected. Then I thought maybe there was something like a DjangoJSONDecoder, but nothing. what am I doing wrong? is this the expected behavior?

like image 451
maraujop Avatar asked Apr 17 '13 07:04

maraujop


2 Answers

It can't work how you think it should. The point is that JSON has no native type for dates/times, which is why the Django serializer converts datetimes to strings. But, of course, once they're strings, then they're strings; the deserializer has no way of knowing that they were once datetimes. You could, if you like, write a further custom deserializer that attempts to call strptime on each string, to see if it "should" be a datetime; but the overhead will be huge, and (depending on your data) could be subject to false positives.

like image 61
Daniel Roseman Avatar answered Nov 06 '22 13:11

Daniel Roseman


You did not specify custom decoder class for json.loads (cls kwarg)

like image 1
Pawel Furmaniak Avatar answered Nov 06 '22 13:11

Pawel Furmaniak