小猿圈詳解Python中Json與object轉(zhuǎn)化的方法

最近部分學(xué)員在學(xué)習(xí)python,對于python里面的有些內(nèi)容不是很了解,下面每天小猿圈python講師就會(huì)為大家準(zhǔn)備一個(gè)小的知識(shí)點(diǎn),希望對你學(xué)習(xí)python有一定的幫助,今天為你分享的是Json與object轉(zhuǎn)化的方法。

Python提供了json包來進(jìn)行json處理,json與python中數(shù)據(jù)類型對應(yīng)關(guān)系如下:

一個(gè)python object無法直接與json轉(zhuǎn)化,只能先將對象轉(zhuǎn)化成dictionary,再轉(zhuǎn)化成json;對json,也只能先轉(zhuǎn)換成dictionary,再轉(zhuǎn)化成object,通過實(shí)踐,源碼如下:

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轉(zhuǎn)換成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轉(zhuǎn)換成object

class userDecode(json.JSONDecoder):

? def decode(self, s):

? ? dic = super().decode(s)

? ? return user(dic['name'], dic['pwd'])

#重寫JSONDecoder的__init__方法,dict轉(zhuǎn)換成object

class userDecode2(json.JSONDecoder):

? def __init__(self):

? ? json.JSONDecoder.__init__(self, object_hook=dic2objhook)

# 對象轉(zhuǎn)換成dict

def obj2dict(obj):

? if (isinstance(obj, user)):

? ? return {

? ? ? 'name': obj.name,

? ? ? 'pwd': obj.pwd

? ? }

? else:

? ? return obj

# dict轉(zhuǎn)換為對象

def dic2objhook(dic):

? if isinstance(dic, dict):

? ? return user(dic['name'], dic['pwd'])

? return dic

# 第一種方式,直接把對象先轉(zhuǎn)換成dict

u = user('smith', '123456')

uobj = json.dumps(obj2dict(u))

print('uobj: ', uobj)

#第二種方式,利用json.dumps的關(guān)鍵字參數(shù)default

u = user('smith', '123456')

uobj2 = json.dumps(u, default=obj2dict)

print('uobj2: ', uobj)

#第三種方式,定義json的encode和decode子類,使用json.dumps的cls默認(rèn)參數(shù)

user_encode_str = json.dumps(u, cls=userEncoder)

print('user2json: ', user_encode_str)

#json轉(zhuǎn)換為object

u2 = json.loads(user_encode_str, cls=userDecode)

print('json2user: ', u2)

#另一種json轉(zhuǎn)換成object的方式

u3 = json.loads(user_encode_str, cls=userDecode2)

print('json2user2: ', u3)

輸出結(jié)果如下:

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

以上就是關(guān)于小猿圈python講師對Json與object轉(zhuǎn)化的方法,希望本文所述對大家有所幫助,最后想要了解更多關(guān)于Python和人工智能方面內(nèi)容的小伙伴,請關(guān)注小猿圈在線學(xué)習(xí)教育平臺(tái)為您提供權(quán)威的Python開發(fā)環(huán)境搭建視頻,學(xué)習(xí)Python后的前景無限,行業(yè)薪資和未來的發(fā)展會(huì)越來越好的。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容