6

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?

2 Answers 2

9

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.

1
  • Thanks, I thought JSON had date/time support, but checking now there's an effort to standardize on ISO 8601. Knowing this, I will tackle the problem in a different way.
    – maraujop
    Apr 17, 2013 at 8:29
1

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

2
  • 5
    json.loads(encoded, cls=DjangoJSONEncoder) like this ? This raises AttributeError: 'DjangoJSONEncoder' object has no attribute 'decode'
    – maraujop
    Apr 17, 2013 at 7:58
  • 2
    @maraujop DjangoJSONEncoder encodes values (.dumps them), so can't be used in .loads. You might implement your own decoder that know what it will parse. Otherwise it would be guessing.
    – Kangur
    Nov 6, 2019 at 15:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.