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?
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.
You did not specify custom decoder class for json.loads
(cls
kwarg)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With