首页 / 操作系统 / Linux / Python中自定义类对象json字符串化的方法
Python中自定义类对象json字符串化的方法1. 用 json 或者simplejson 就可以2.定义转换函数:def convert_to_builtin_type(obj): print "default(", repr(obj), ")" # 把MyObj对象转换成dict类型的对象d = { }d.update(obj.__dict__)return d3. 定义类class Object():
name=""
size=0
def __init__(self,name", size,):
self.name"= name"
self.size = size
4. 生成对象obj= Object(name, size)5.dumps执行,引入转换函数print json.dumps(obj, default=convert_to_builtin_type)特别说明,如果是python的内置对象,如列表,float,str等,不需要转换函数。 否则json模块默认是没法处理的,会抛出异常:TypeError xx is not JSON serializablePython 的详细介绍:请点这里
Python 的下载地址:请点这里推荐阅读:Python正则表达式介绍及使用方法 http://www.linuxidc.com/Linux/2013-10/90832.htmPython中的sorted函数以及operator.itemgetter函数 http://www.linuxidc.com/Linux/2013-10/90820.htmPython+Django 快速建立简易blog http://www.linuxidc.com/Linux/2013-09/90636.htm[Python] 安装及环境配置 http://www.linuxidc.com/Linux/2013-09/90278.htmPython算法之插入排序 http://www.linuxidc.com/Linux/2013-09/89929.htmPython 删除某个路径下所有文件及模块调用注意事项 http://www.linuxidc.com/Linux/2013-09/89752.htmUbuntu 12.04下源代码安装MySQL5.6以及Python-MySQLdb http://www.linuxidc.com/Linux/2013-08/89270.htm用Python备份MySQL数据库的脚本 http://www.linuxidc.com/Linux/2013-08/88589.htm