Python json 错误xx is not JSON serializable解决办法

作者:orangleliu 时间:2021-06-25 21:58:05 

Python json 错误xx is not JSON serializable解决办法

在使用json的时候经常会遇到xxx  is not JSON serializable,也就是无法序列化某些对象。经常使用django的同学知道django里面有个自带的Encoder来序列化时间等常用的对象。其实我们可以自己定定义对特定类型的对象的序列化,下面看下怎么定义和使用的。


#!/usr/bin/env python
# -*- coding: utf-8 -*-
#json_extention
#2014-03-16
#copyright: orangleliu
#license: BSD

'''''
python中dumps方法很好用,可以直接把我们的dict直接序列化为json对象
但是有的时候我们加了一些自定义的类就没法序列化了,这个时候需要
自定义一些序列化方法

参考:
http://docs.python.org/2.7/library/json.html

例如:
In [3]: from datetime import datetime

In [4]: json_1 = {'num':1112, 'date':datetime.now()}

In [5]: import json

In [6]: json.dumps(json_1)
---------------------------------------------------------------------------
TypeError                 Traceback (most recent call last)
D:\devsofts\python2.7\lib\site-packages\django\core\management\commands\shell.py
c in <module>()
----> 1 json.dumps(json_1)

TypeError: datetime.datetime(2014, 3, 16, 13, 47, 37, 353000) is not JSON serial
izable
'''

from datetime import datetime
import json

class DateEncoder(json.JSONEncoder ):
 def default(self, obj):
   if isinstance(obj, datetime):
     return obj.__str__()
   return json.JSONEncoder.default(self, obj)

json_1 = {'num':1112, 'date':datetime.now()}
print json.dumps(json_1, cls=DateEncoder)

'''''
输出结果:

PS D:\code\python\python_abc> python .\json_extention.py
{"date": "2014-03-16 13:56:39.003000", "num": 1112}
'''

#我们自定义一个类试试
class User(object):
 def __init__(self, name):
   self.name = name

class UserEncoder(json.JSONEncoder):
 def default(self, obj):
   if isinstance(obj, User):
     return obj.name
   return json.JSONEncoder.default(self, obj)

json_2 = {'user':User('orangle')}
print json.dumps(json_2, cls=UserEncoder)

'''''
PS D:\code\python\python_abc> python .\json_extention.py
{"date": "2014-03-16 14:01:46.738000", "num": 1112}
{"user": "orangle"}

'''

定义处理方法是继承json.JSONEncoder的一个子类,使用的时候是在dumps方法的cls函数中添加自定义的处理方法。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

来源:http://blog.csdn.net/orangleliu/article/details/21324459

标签:Python,JSON,serializable
0
投稿

猜你喜欢

  • Python网络编程之xmlrpc模块

    2023-04-06 15:19:24
  • 比较一下看看自己掌握了多少SQL快捷键

    2009-01-04 14:04:00
  • 在Python中使用M2Crypto模块实现AES加密的教程

    2022-09-29 17:43:59
  • python小项目之五子棋游戏

    2022-07-12 06:24:23
  • python脚本框架webpy的url映射详解

    2021-10-27 18:55:05
  • python执行系统命令后获取返回值的几种方式集合

    2022-07-24 22:43:56
  • Django后台获取前端post上传的文件方法

    2023-04-11 10:57:26
  • 和“登录”有关的事儿

    2009-07-10 17:37:00
  • html网页颜色表大全(苏昱)

    2008-01-01 15:52:00
  • mysql 修改表结构 判断并添加column

    2010-10-25 20:07:00
  • JS如何获取变量值

    2008-05-18 12:52:00
  • PJBlog3优化——单击自动输入验证码

    2009-05-17 11:03:00
  • 详解MySQL数据库之更新语句

    2010-08-08 09:15:00
  • python 图片验证码代码

    2023-07-22 00:33:19
  • python实现批量提取指定文件夹下同类型文件

    2023-11-17 17:13:31
  • 快速上手基于Anaconda搭建Django环境的教程

    2021-07-02 22:07:13
  • 用Python编写一个每天都在系统下新建一个文件夹的脚本

    2021-11-08 22:39:16
  • 数据库安全应用 使用MySQL的23个注意事项

    2009-05-13 10:27:00
  • 用户体验 保守的使用下拉菜单

    2008-01-15 20:00:00
  • Python使用代理抓取网站图片(多线程)

    2023-06-25 17:34:50
  • asp之家 网络编程 m.aspxhome.com