1. 程式人生 > >關於在Django中Json無法序列化datetime的解決辦法

關於在Django中Json無法序列化datetime的解決辦法

ngs spec `` keys 定義 列表 ror 內置 cat

  

  我們在網頁設計時經常會在前端和後臺進行交互,前端回傳的方法可以時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)
json.dumps源碼

  其中提到了:

技術分享

  所以我們可以嘗試自定義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的解決辦法