我们在网页设计时经常会在前端和后台进行交互,前端回传的方法可以时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. img alt与title的区别

    前端 alt是图片加载不出来时候,对图片的文本替代 title 是鼠标放在图片上时,对图片的进一步说明 seo 搜索引擎对图片意思的理解主要靠 alt

  2. 【学习笔记】Hibernate关联映射(Y2-1-6)

    Hibernate关联映射 关联映射就是将关联关系映射到数据库里,在对象模型中就是一个或多个引用. 1.单向多对一关联 准备数据库 部门表和员工表 其中部门表有两列 部门编号和名称 员工表有三列 员工 ...

  3. Python数据结构之四——set(集合)

    Python版本:3.6.2  操作系统:Windows  作者:SmallWZQ 经过几天的回顾和学习,我终于把Python 3.x中的基础知识介绍好啦.下面将要继续什么呢?让我想想先~~~嗯,还是 ...

  4. 【转载】什么是Windows USB设备路径,它是如何格式化的?

    http://blog.csdn.net/kingmax54212008/article/details/77837210 用于接口的复合USB设备路径格式 \?usb#vid_ vvvv&p ...

  5. UVA 10534最长上升子序列运用

    在给定序列中寻找一个1~n+1递增,n~2n+1递减的序列,我的想法是直接对原序列和原序列的反序列用nlgn算法求递增序列,例如序列a[]={1,2,4,1,2,6},它的反序列为b[]={6,2,1 ...

  6. java定时任务(三):timerTask定时任务

    这种方式是纯粹的java代码,需要继承timerTask接口并重写run方法,创建这个类的时候就会调用run方法. 基本的使用逻辑是: 把自己需要处理的业务逻辑放在自己写的这个继承了timerTask ...

  7. Hello China操作系统在Virtual PC上的安装和使用

    http://blog.csdn.net/hellochina15/article/details/7253350 本文介绍如何在Windows 7操作系统和Virtual PC 2007虚拟机上安装 ...

  8. 引导加载程序之争: LILO 和 GRUB

    在不考虑他们的工作或专业情况下,所有 Linux 用户都会使用的是哪个工具?引导加载程序.通过本文了解引导加载程序的工作原理,认识两个流行的引导加载程序 LILO(LInux LOader)和 GNU ...

  9. 使用jsoup抓取新闻信息

    1,jsoup简介 jsoup 是一款Java 的HTML解析器,可直接解析某个URL地址.HTML文本内容.它提供了一套非常省力的API,可通过DOM,CSS以及类似于jQuery的操作方法来取出和 ...

  10. HTML5之Canvas画圆形

    HTML5之Canvas画圆形 1.设计源码 <!DOCTYPE html> <head> <meta charset="utf-8" /> & ...