关于在Django中Json无法序列化datetime的解决办法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了关于在Django中Json无法序列化datetime的解决办法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3353字,纯文字阅读大概需要5分钟。
内容图文
我们在网页设计时经常会在前端和后台进行交互,前端回传的方法可以时redirect一个地址加上显式的参数,第二个办法就是使用Ajax结构。那么在传到view函数中进行处理后是需要通过Json格式进行返回给前端,不然前端时不认识返回的数据,此时就需要使用到Json的序列化。
如果是从数据库中取的数据往往时queryset类型,Json无法直接序列化,需要先将其用list转成列表的形式再进行json,此方法可以解决大部分的问题,但是如果数据中包含datetime类型json就会报错。无法对其序列化,显示如下:
看源码,问题出在哪里?
从源码中我们可以看到json只能序列化str类型的数据。那么就没别的办法了吗?
方法一
我们再来看源码:
def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw): """Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is true then ``dict`` keys that are not basic types (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is false, then the return value can contain non-ASCII characters if they appear in strings contained in ``obj``. Otherwise, all such characters are escaped in JSON strings. If ``check_circular`` is false, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is false, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If ``indent`` is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. ``None`` is the most compact representation. If specified, ``separators`` should be an ``(item_separator, key_separator)`` tuple. The default is ``(‘, ‘, ‘: ‘)`` if *indent* is ``None`` and ``(‘,‘, ‘: ‘)`` otherwise. To get the most compact JSON representation, you should specify ``(‘,‘, ‘:‘)`` to eliminate whitespace. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. If *sort_keys* is true (default: ``False``), then the output of dictionaries will be sorted by key. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg; otherwise ``JSONEncoder`` is used. """# cached encoderif (not skipkeys and ensure_ascii and check_circular and allow_nan and cls is None and indent is None and separators is None and default is None andnot sort_keys andnot kw): return _default_encoder.encode(obj) if cls is None: cls = JSONEncoder return cls( skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, default=default, sort_keys=sort_keys, **kw).encode(obj) _default_decoder = JSONDecoder(object_hook=None, object_pairs_hook=None)
其中提到了:
所以我们可以尝试自定义JsonEncoder:
class CJSONEncoder(self,o): if isinstance(o,datetime.datetime): return o.strftime("%Y-%m-%d %H-%M-%S") if isinstance(o,datetime.date): return o.strftime("%Y-%m-%d") else:reture json.JSONEncoder.default(self,o)
然后在Json序列化时使用 json.dumps(data,cls = CJSONEncoder)
方法2:
如果取数据库的时候没有外键的话还可以使用django内置的方法:import django.core中的serializers,专用于序列化queryset类 data = serializers.serialize(‘json‘,data) 直接可将queryset序列化,局限就在与对外键的支持不够好。
原文:http://www.cnblogs.com/BigJ/p/7627139.html
内容总结
以上是互联网集市为您收集整理的关于在Django中Json无法序列化datetime的解决办法全部内容,希望文章能够帮你解决关于在Django中Json无法序列化datetime的解决办法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。