我们在网页设计时经常会在前端和后台进行交互,前端回传的方法可以时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的解决办法的更多相关文章

  1. TypeError: datetime.datetime(2016, 9, 25, 21, 12, 19, 135649) is not JSON serializable解决办法(json无法序列化对象的解决办法)

    1.一个简单的方法来修补json模块,这样序列将支持日期时间. import json import datetime json.JSONEncoder.default = lambda self, ...

  2. ASP.NET中JSON的序列化和反序列化

    JSON是专门为浏览器中的网页上运行的JavaScript代码而设计的一种数据格式.在网站应用中使用JSON的场景越来越多,本文介绍 ASP.NET中JSON的序列化和反序列化,主要对JSON的简单介 ...

  3. ASP.NET 中JSON 的序列化和反序列化

    JSON是专门为浏览器中的网页上运行的JavaScript代码而设计的一种数据格式.在网站应用中使用JSON的场景越来越多,本文介绍ASP.NET中JSON的序列化和反序列化,主要对JSON的简单介绍 ...

  4. ASP.NET中JSON的序列化和反序列化(转)

    JSON是专门为浏览器中的网页上运行的JavaScript代码而设计的一种数据格式.在网站应用中使用JSON的场景越来越多,本文介绍ASP.NET中JSON的序列化和反序列化,主要对JSON的简单介绍 ...

  5. [转]ASP.NET中JSON的序列化和反序列化

    本文转自:http://www.cnblogs.com/zhaozhan/archive/2011/01/09/1931340.html JSON是专门为浏览器中的网页上运行的JavaScript代码 ...

  6. Asp.net中Json的序列化和反序列化(一)

    JSON是专门为浏览器中的网页上运行的JavaScript代码而设计的一种数据格式.在网站应用中使用JSON的场景越来越多,本文介绍ASP.NET中JSON的序列化和反序列化,主要对JSON的简单介绍 ...

  7. 工作总结 EntityFramework中出现DateTime2异常的完美解决办法

    EntityFramework中出现DateTime2异常的完美解决办法   今天在使用entityframework往数据库插入数据的时候,突然出现了一个数据类型转换异常的问题: System.Da ...

  8. IIS关于“ 配置错误 不能在此路径中使用此配置节”的解决办法

    IIS关于“ 配置错误 不能在此路径中使用此配置节”的解决办法 原文链接:http://www.cnblogs.com/200325074/p/3679316.html 今天刚安装好IIS8.5, 我 ...

  9. Excel在任务栏中只显示一个窗口的解决办法

     Excel在任务栏中只显示一个窗口的解决办法  以前朋友遇到过这个问题,这次自己又遇到了,习惯了以前的那种在任务栏中显示全部窗口,方便用Alt+Tab键进行切换. 如果同时打开许多Excel工作簿, ...

随机推荐

  1. angular ng build --prod 打包报错解决方案

    使用以下代码  就不报错了 ng build --prod --no-extract-license    打包命令 使用以下代码  就不报错了 ng build --prod --no-extrac ...

  2. 原创~vue router-link添加点击事件

    在学习vue中会遇到给router-link添加@click,@mouseover等事件 我想要做的是用v-for循环输出导航菜单,但是下面代码的@click事件和@mouseover并不会响应 &l ...

  3. 浅谈format格式化输出

    什么是format? 相对于基本格式化输出采用"%"的方法,format的功能强大,该函数把字符串当一个模板,通过传入的参数进行格式化,并且使用大括号"{}"作 ...

  4. Mock摆脱后端拖拉(借鉴官网)(一)

    mock是一个模拟数据生成器,旨在帮助前端独立于后端进行开发,帮助编写单元测试.mock有如下功能 根据数据模板生成模板数据 模拟ajax请求,生成请求数据 基于html模板生成模拟数据 下载安装 n ...

  5. js中的回调函数

    1.你定义的 2.你没有调用 3.但是最终他执行了 例子: 定时器回调函数 setTimeout(function(){ },100); dom元素的回调函数 document.getElementB ...

  6. Nginx location配置详细解释

    nginx location配置详细解释 语法规则: location [=|~|~*|^~] /uri/ { - } = 开头表示精确匹配 ^~ 开头表示uri以某个常规字符串开头,理解为匹配 ur ...

  7. 2018年最完整5大网页设计图标解决方案:Font Awesome奥森图Unicode、CSS 和、Font以及国产zfont图标集

    网上有很多高质量的图标,基于icon的关键词能在Google上搜索到不少内容,不考虑版权外还要修改大小.颜色等等,现在介绍一些替代方案:Unicode.CSS 和 Font,它具有更高的灵活性. 方案 ...

  8. Python 关于super 的 用法和原理(挖坑)

    一.前言 Python 面向对象中有继承这个概念,初学时感觉很牛逼,里面也有个super类,经常见到,最近做一些题才算是理解了.特地记录分享给后来研究的小伙伴,毕竟现在小学生都开始学了(滑稽脸) 二. ...

  9. JavaScript网页全屏API

    在大多数的浏览器中都有实现网页全屏显示的功能,并且大部分浏览器实现全屏显示和退出全屏显示的快捷键通常是F11和Esc两个按键.如今,W3C已经制定了关于网页全屏显示的API,利用这个API 可以实现网 ...

  10. 对于JAVA程序优化的一些想法,读书有感.治疗强迫症良药

    在深入了解Java虚拟机里读到:在try{}块里面执行代码,比if(x!=null)效率要高,前提是被catch的几率很低的情况下. 但是 在Effective Java里读到:因为异常机制的设计初衷 ...