关于在Django中Json无法序列化datetime的解决办法
Posted KeepLearningEverday
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于在Django中Json无法序列化datetime的解决办法相关的知识,希望对你有一定的参考价值。
我们在网页设计时经常会在前端和后台进行交互,前端回传的方法可以时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 encoder if (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 and not sort_keys and not 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序列化,局限就在与对外键的支持不够好。
以上是关于关于在Django中Json无法序列化datetime的解决办法的主要内容,如果未能解决你的问题,请参考以下文章
django json序列化程序不实现geojson [重复]