我们在网页设计时经常会在前端和后台进行交互,前端回传的方法可以时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. CSS布局(五) 网页布局方式

    网页实质是块与块之间的位置,块挨着块,块嵌套块,块叠着块. 三种关系:相邻,嵌套,重叠. 下面介绍网页布局的常用几种方式 1.一列布局: 一般都是固定的宽高,设置margin : 0 auto来水平居 ...

  2. 修改maven项目jdk版本,并解决Dynamic Web Module 3.1 requires Java 1.7 or newer错误

    使用maven的时候,默认会使用1.5版本的JDK,并且创建项目时也会是1.5版本. 但是我想用JDK1.7版本,所以我手动将maven项目JDK改为1.7版本. 手动修改JDK版本为1.7以后,项目 ...

  3. mysql 学习心得1

    1由于不靠这玩意吃饭 估计不准备精读 顺便中文版也不用担心翻译问题 科科 大致翻了下=,= mysql的感觉怎么就是背命令.... 2DDL语句 定义数据 创建删除修改 create drop alt ...

  4. uva 1583

    枚举1~100000把所有数的最小generators记录下来,直接查表即可. AC代码: #include<cstdio> #include<cstring> #includ ...

  5. hdu1394 分治 or 线段树

    利用分治求一次逆序数,然后每次把第一个元素放到末尾,设该交换元素的值为x,设上一次求得的逆序数为y,那么此时的逆序数等于y - x + (n - x - 1),减去x是因为x作为第一个元素,其后共有x ...

  6. Python基础学习参考(七):字典和集合

    一.字典 字典跟列表一样是一组数据的集合.它的特点是什么呢? 特点一:字典具有键(key)和值(value),其中键必须是唯一的,不可重复的,即键必须可以哈希的.对于值没有要求. 特点二:字典是无序的 ...

  7. ORACLE透明网关访问SQL Server配置总结

      透明网关概念 ORACLE透明网关(Oracle Transparent Gateway)可以解决ORACLE数据库和非ORACLE数据库交互数据的需求.在一个异构的分布式环境中,通过ORACLE ...

  8. 迁移学习︱艺术风格转化:Artistic style-transfer+ubuntu14.0+caffe(only CPU)

    说起来这门技术大多是秀的成分高于实际,但是呢,其也可以作为图像增强的工具,看到一些比赛拿他作训练集扩充,还是一个比较好的思路.如何在caffe上面实现简单的风格转化呢? 好像网上的博文都没有说清楚,而 ...

  9. HighCharts之2D颜色阶梯饼图

    HighCharts之2D颜色阶梯饼图 1.实例源码 PieGradient.html: <!DOCTYPE html> <html> <head> <met ...

  10. Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.h2.Driver

    1.错误描述 WARN:2015-05-01 13:26:10[localhost-startStop-1] - HHH000402: Using Hibernate built-in connect ...