Reputation: 4594
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?
Upvotes: 7
Views: 7032
Reputation: 599600
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.
Upvotes: 10
Reputation: 4806
You did not specify custom decoder class for json.loads
(cls
kwarg)
Upvotes: 1