您的位置:首页技术文章
文章详情页

Python 之 Json序列化嵌套类方式

【字号: 日期:2022-08-05 15:25:43浏览:3作者:猪猪

想要用python自已手动序列化嵌套类,就要明白两个问题:

1.Json是什么?

2.Json支持什么类型?

答案显而易见

Json就是嵌套对象

Json在python中支持列表,字典(当然也支持int,string.....,不过说这个也没多大必要)

很好,等等,列表,字典?我们在python中学过列表,字典,字典列表,列表字典,字典字典,那,我们可不可以把类对象转化为这些呢?

我可以很确定的告诉你,可以,并且,嵌套类都可以!!!

下面就来实战:

from flask import Flaskimport json app = Flask(__name__) class City(): def __init__(self,country,provider): self.country = country self.provider = provider class School(): def __init__(self,country,provider,name,nums): self.city = City(country,provider) self.name = name self.nums = nums @app.route(’/method0’)def method0(): school = School(’china’,’shanxi’,’wutaizhongxue’,’2000’) s_temp0 = [school.city.country,school.city.provider,school.name,school.nums] return json.dumps(s_temp0) @app.route(’/method1’)def method1(): school = School(’china’,’shanxi’,’wutaizhongxue’,’2000’) s_temp1 = {’country’:school.city.country,’provider’:school.city.provider,’name’:school.name,’nums’:school.nums} return json.dumps(s_temp1) @app.route(’/method2’)def method2(): school = School(’china’,’shanxi’,’wutaizhongxue’,’2000’) s_temp2 = [{’country’:school.city.country,’provider’:school.city.provider},school.name,school.nums] return json.dumps(s_temp2) @app.route(’/method3’)def method3(): school = School(’china’,’shanxi’,’wutaizhongxue’,’2000’) s_temp3 = {’city’:[school.city.country,school.city.provider],’name’:school.name,’nums’:school.nums} return json.dumps(s_temp3) @app.route(’/method4’)def method4(): school = School(’china’,’shanxi’,’wutaizhongxue’,’2000’) s_temp4 = {’city’:{’country’:school.city.country,’provider’:school.city.provider},’name’:school.name,’nums’:school.nums} return json.dumps(s_temp4) if __name__ == ’__main__’: app.run(debug=True)

执行效果:

Python 之 Json序列化嵌套类方式

Python 之 Json序列化嵌套类方式

Python 之 Json序列化嵌套类方式

Python 之 Json序列化嵌套类方式

Python 之 Json序列化嵌套类方式

很多人会说,第五种才是我想要的,前面四种不是标准的json数据,刚开始确实是这样认为的,但是。。。

1.如果你处理的两个嵌套类是数据库的呢?假比如一对多的关系型数据库,method3不是一个很好的选择么?

2.如果你处理的两个嵌套类是包含关系呢?method2不是一个很好的选择么?

以上这篇Python 之 Json序列化嵌套类方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持好吧啦网。

标签: Python 编程
相关文章: