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?

maraujop
  • 4,472
  • 2
  • 36
  • 40

2 Answers2

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.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 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 '13 at 08:29
1

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

Pawel Furmaniak
  • 4,648
  • 3
  • 29
  • 33
  • 5
    `json.loads(encoded, cls=DjangoJSONEncoder)` like this ? This raises `AttributeError: 'DjangoJSONEncoder' object has no attribute 'decode'` – maraujop Apr 17 '13 at 07: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 06 '19 at 15:26