想要用python自已手动序列化嵌套类,就要明白两个问题:
1.Json是什么?
2.Json支持什么类型?
答案显而易见
Json就是嵌套对象
Json在python中支持列表,字典(当然也支持int,string.....,不过说这个也没多大必要)
很好,等等,列表,字典?我们在python中学过列表,字典,字典列表,列表字典,字典字典,那,我们可不可以把类对象转化为这些呢?
我可以很确定的告诉你,可以,并且,嵌套类都可以!!!
下面就来实战:
from flask import Flask import 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)
执行效果:
很多人会说,第五种才是我想要的,前面四种不是标准的json数据,刚开始确实是这样认为的,但是。。。
1.如果你处理的两个嵌套类是数据库的呢?假比如一对多的关系型数据库,method3不是一个很好的选择么?
2.如果你处理的两个嵌套类是包含关系呢?method2不是一个很好的选择么?
以上这篇Python 之 Json序列化嵌套类方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月25日
2024年09月25日
- 纯音入心系列纯音乐《天籁古筝》1CD[MP3][331MB]
- 男女对唱典藏天碟《发烧对唱·那个季节里的歌DSD》10CD[WAV]
- 群星2010-歌林精选辑[歌林][WAV+CUE]
- TrioZimbalist-PianoTriosofWeinberg,Auerbach,Dvorak(2024)[24-44,1]wav
- 群星.1992-滚石第一流台湾歌·12王牌大车拼【滚石】【WAV+CUE】
- 林子祥.1984-创作歌集【华纳】【WAV+CUE】
- 周汤豪.2010-周汤豪【华纳】【FLAC分轨】
- Mozart-TheStringQuintets-AmadeusQuartet,CecilAronowitz(2017)[24-44,1][WAV+CUE]
- JamesWilliamsDennisIrwin-Focus(2024,Red)[24-48]FLAC
- 藤泽麻衣《空みあげて》[WAV]
- 纯音入心系列纯音乐《中国古筝经典名曲》1CD[MP3][1.3GB]
- 纯音入心系列纯音乐《古筝新奏:岁月静好与筝语,细水流年与筝同》1CD[MP3][846.9MB]
- 670《脆弱敏感小女生》[320K/MP3][27.53MB]
- 曾琳.2011-好好爱我【南方】【WAV+CUE】
- 范晓萱.1995-RAIN【福茂】【WAV+CUE】