这篇文章主要为大家详细介绍了怎么中python中对Json与object进行转换,文中示例代码介绍的非常详细,具有一定的参考价值,发现的小伙伴们可以参考一下:
Python是一种跨平台的、具有解释性、编译性、互动性和面向对象的脚本语言,其最初的设计是用于编写自动化脚本,随着版本的不断更新和新功能的添加,常用于用于开发独立的项目和大型项目。
python提供了json包来进行json处理,json与python中数据类型对应关系如下:
一个python object无法直接与json转化,只能先将对象转化成dictionary,再转化成json;对json,也只能先转换成dictionary,再转化成object,通过实践,源码如下:
import json
class user:
def __init__(self, name, pwd):
self.name = name
self.pwd = pwd
def __str__(self):
return 'user(' + self.name + ',' + self.pwd + ')'
#重写JSONEncoder的default方法,object转换成dict
class 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转换成object
class userDecode(json.JSONDecoder):
def decode(self, s):
dic = super().decode(s)
return user(dic['name'], dic['pwd'])
#重写JSONDecoder的__init__方法,dict转换成object
class userDecode2(json.JSONDecoder):
def __init__(self):
json.JSONDecoder.__init__(self, object_hook=dic2objhook)
# 对象转换成dict
def 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
# 第一种方式,直接把对象先转换成dict
u = user('smith', '123456')
uobj = json.dumps(obj2dict(u))
print('uobj: ', uobj)
#第二种方式,利用json.dumps的关键字参数default
u = 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转换为object
u2 = 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.py
uobj: {"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
以上就是亿速云小编为大家收集整理的怎么中python中对Json与object进行转换,如何觉得亿速云网站的内容还不错,欢迎将亿速云网站推荐给身边好友。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。