Django JSON自定义序列化丢失的日期时间类型 [英] Django JSON custom serializing losing datetime type

查看:75
本文介绍了Django JSON自定义序列化丢失的日期时间类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django json库对从Django游标中获取的数据进行编码,但是我看到反序列化后的日期时间现在是unicode类型.简单的例子:

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

如果我没记错的话,应该尊重变量类型.然后,我想也许有类似DjangoJSONDecoder的东西,但是什么也没有.我究竟做错了什么?这是预期的行为吗?

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?

推荐答案

您认为应该的方法不起作用.关键是JSON没有日期/时间的本机类型,这就是Django序列化程序将日期时间转换为字符串的原因.但是,当然,一旦它们成为字符串,那么它们就是字符串.反序列化器无法知道它们曾经是日期时间.如果愿意,您可以 编写一个进一步的自定义反序列化器,尝试对每个字符串调用 strptime ,以查看它是否应该"为日期时间;但是开销会很大,并且(取决于您的数据)可能会受到误报.

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.

这篇关于Django JSON自定义序列化丢失的日期时间类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆