python中Json与object转化
来源:互联网 发布:windows longhorn 下载 编辑:程序博客网 时间:2024/05/15 20:23
python提供了json包来进行json处理,json与python中数据类型对应关系如下:
一个python object无法直接与json转化,只能先将对象转化成dictionary,再转化成json;对json,也只能先转换成dictionary,再转化成object,通过实践,源码如下:
import jsonclass user: def __init__(self, name, pwd): self.name = name self.pwd = pwd def __str__(self): return 'user(' + self.name + ',' + self.pwd + ')'#重写JSONEncoder的default方法,object转换成dictclass userEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, user): return { 'name': o.name, 'pwd': o.pwd } return json.JSONEncoder.default(o)#重写JSONDecoder的decode方法,dict转换成objectclass userDecode(json.JSONDecoder): def decode(self, s): dic = super().decode(s) return user(dic['name'], dic['pwd'])#重写JSONDecoder的__init__方法,dict转换成objectclass userDecode2(json.JSONDecoder): def __init__(self): json.JSONDecoder.__init__(self, object_hook=dic2objhook)# 对象转换成dictdef obj2dict(obj): if (isinstance(obj, user)): return { 'name': obj.name, 'pwd': obj.pwd } else: return obj# dict转换为对象def dic2objhook(dic): if isinstance(dic, dict): return user(dic['name'], dic['pwd']) return dic# 第一种方式,直接把对象先转换成dictu = user('smith', '123456')uobj = json.dumps(obj2dict(u))print('uobj: ', uobj)#第二种方式,利用json.dumps的关键字参数defaultu = user('smith', '123456')uobj2 = json.dumps(u, default=obj2dict)print('uobj2: ', uobj)#第三种方式,定义json的encode和decode子类,使用json.dumps的cls默认参数user_encode_str = json.dumps(u, cls=userEncoder)print('user2json: ', user_encode_str)#json转换为objectu2 = json.loads(user_encode_str, cls=userDecode)print('json2user: ', u2)#另一种json转换成object的方式u3 = json.loads(user_encode_str, cls=userDecode2)print('json2user2: ', u3)
输出结果如下:
C:\python\python.exe C:/Users/Administrator/PycharmProjects/pytest/com/guo/myjson.pyuobj: {"name": "smith", "pwd": "123456"}uobj2: {"name": "smith", "pwd": "123456"}user2json: {"name": "smith", "pwd": "123456"}json2user: user(smith,123456)json2user2: user(smith,123456)Process finished with exit code 0
0 0
- python中Json与object转化
- 在C# 中 object 转化 Json
- Object转化成JSON字符串
- xml。。。json。。。object之间转化
- java中string与json互相转化
- js中:json对象与字符串转化
- java中string与json互相转化
- java中string与json互相转化
- java中string与json互相转化
- python json转化操作
- 玩转Web之Json(四)---json与(Object/List/Map)的相互转化
- JS中json对象与json字符串互相转化
- python 转化object 到json 然后存入redis以及从redis读取
- python中的数据类型与json的数据类型之间的转化
- 【python】复杂对象的创建过程与转化为json
- json 与 string 转化
- 数据类型json 和 object 的相互转化
- freemarker 将object转化为json类型
- jdbc 的介绍
- Unity陀螺仪
- 京东商品详情页前端开发宝典
- build 失败 jre1.8
- select、poll、epoll之间的区别总结[整理]
- python中Json与object转化
- Codeforces-704A-Thor
- tomcat目录结构及配置文件说明
- 晨魅--开机显示器显示无信号解决方法
- 【杭电2084】
- Python中__init__.py文件的作用
- hdu4810 Wall Painting 【组合数学】
- Codeforces-703A-Mishka and Game
- Windows 64位下安装Redis超详细教程