Python 之 Json序列化嵌套類方式
想要用python自已手動(dòng)序列化嵌套類,就要明白兩個(gè)問題:
1.Json是什么?
2.Json支持什么類型?
答案顯而易見
Json就是嵌套對(duì)象
Json在python中支持列表,字典(當(dāng)然也支持int,string.....,不過說(shuō)這個(gè)也沒多大必要)
很好,等等,列表,字典?我們?cè)趐ython中學(xué)過列表,字典,字典列表,列表字典,字典字典,那,我們可不可以把類對(duì)象轉(zhuǎn)化為這些呢?
我可以很確定的告訴你,可以,并且,嵌套類都可以?。?!
下面就來(lái)實(shí)戰(zhàn):
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)
執(zhí)行效果:





很多人會(huì)說(shuō),第五種才是我想要的,前面四種不是標(biāo)準(zhǔn)的json數(shù)據(jù),剛開始確實(shí)是這樣認(rèn)為的,但是。。。
1.如果你處理的兩個(gè)嵌套類是數(shù)據(jù)庫(kù)的呢?假比如一對(duì)多的關(guān)系型數(shù)據(jù)庫(kù),method3不是一個(gè)很好的選擇么?
2.如果你處理的兩個(gè)嵌套類是包含關(guān)系呢?method2不是一個(gè)很好的選擇么?
以上這篇Python 之 Json序列化嵌套類方式就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
解決pandas展示數(shù)據(jù)輸出時(shí)列名不能對(duì)齊的問題
今天小編就為大家分享一篇解決pandas展示數(shù)據(jù)輸出時(shí)列名不能對(duì)齊的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧2019-11-11
Python獲取excel的數(shù)據(jù)并繪制箱型圖和直方圖的方法實(shí)例
這篇文章主要給大家介紹了關(guān)于Python獲取excel的數(shù)據(jù)并繪制箱型圖和直方圖的相關(guān)資料,好的圖表能幫助我們深化數(shù)據(jù)的記憶點(diǎn),文中通過圖文以及代碼示例將實(shí)現(xiàn)的方法介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12
python識(shí)別文字(基于tesseract)代碼實(shí)例
這篇文章主要介紹了python識(shí)別文字(基于tesseract)代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08
python識(shí)別圖像并提取文字的實(shí)現(xiàn)方法
這篇文章主要介紹了python識(shí)別圖像并提取文字的實(shí)現(xiàn)方法,2019-06-06
python獲取外網(wǎng)IP并發(fā)郵件的實(shí)現(xiàn)方法
下面小編就為大家?guī)?lái)一篇python獲取外網(wǎng)IP并發(fā)郵件的實(shí)現(xiàn)方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2017-10-10

