小猿圈002 发表于 2019-5-30 17:00:08

小猿圈详解Python中Json与object转化的方法

最近部分学员在学习python,对于python里面的有些内容不是很了解,下面每天小猿圈python讲师就会为大家准备一个小的知识点,希望对你学习python有一定的帮助,今天为你分享的是Json与object转化的方法。https://upload-images.jianshu.io/upload_images/15397392-09bfab59676b3305.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240


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 = pwddef __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以上就是关于小猿圈python讲师对Json与object转化的方法,希望本文所述对大家有所帮助,最后想要了解更多关于Python和人工智能方面内容的小伙伴,请关注小猿圈在线学习教育平台为您提供权威的Python开发环境搭建视频python自学交流:242719133,学习Python后的前景无限,行业薪资和未来的发展会越来越好的。
页: [1]
查看完整版本: 小猿圈详解Python中Json与object转化的方法