Django JSON custom serializing losing datetime type

荒凉一梦 提交于 2019-11-30 17:18:34

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/16054440/django-json-custom-serializing-losing-datetime-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!