JSON如何快速轉(zhuǎn)成對(duì)象?
“
閱讀本文大概需要 3 分鐘。
我們知道,在 Python 里面,要把 JSON 轉(zhuǎn)成字典是非常容易的,只需要使用json.loads(JSON字符串)就可以了。
但如果這個(gè) JSON 轉(zhuǎn)成的字典,嵌套比較深,那么要讀取里面的數(shù)據(jù)就非常麻煩了。如下圖所示:
如果我要讀取把圖中的end減去start字段,那么用字典的時(shí)候,代碼要寫成這樣:
result = info['data'][0]['entities']['annotations'][0]['end'] - info['data'][0]['entities']['annotations'][0]['start']
光是看到這些方括號(hào)和單引號(hào),就夠讓人頭暈了。
但如果改成下面這樣,看起來就清爽多了:
result = info.data[0].entities.annotations[0].end - info.data[0].entities.annotations[0].start
那么如何快速把一個(gè)嵌套很深的字典轉(zhuǎn)換為對(duì)象呢?其實(shí)非常簡(jiǎn)單,使用 Python 自帶的SimpleNamespace就可以了。
使用SimpleNamespace可以快速創(chuàng)建一個(gè)空對(duì)象,并設(shè)置它的屬性,用法如下:
from types import SimpleNamespace
ins = SimpleNamespace(aa=1, bb=2, cc=3)
print(ins.bb)
運(yùn)行效果如下圖所示:
基于字典創(chuàng)建也非常簡(jiǎn)單:
from types import SimpleNamespace
data = {'aa': 1, 'bb': 2, 'cc': 3}
ins = SimpleNamespace(**data)
print(ins.bb)
對(duì)于深層嵌套的 JSON 字符串,我們?cè)谑褂?code style="font-size:14px;color:rgb(30,107,184);background-color:rgba(27,31,35,.05);font-family:'Operator Mono', Consolas, Monaco, Menlo, monospace;">json.loads時(shí),額外設(shè)置一個(gè)參數(shù):object_hook,就可以實(shí)現(xiàn)遞歸式轉(zhuǎn)換內(nèi)層字典:
x = json.loads(JSON字符串, object_hook=lambda d: SimpleNamespace(**d))
如下圖所示:
關(guān)于參數(shù)object_hook的具體用法,大家可以看官方文檔[1]
參考資料
[1]官方文檔: https://docs.python.org/3/library/json.html#json.loads
End
歡迎大家加入【ChatGPT&AI 變現(xiàn)圈】,零門檻掌握 AI 神器!我們帶你從小白到高手,解鎖智能問答、自動(dòng)化創(chuàng)作、技術(shù)變現(xiàn)的無限可能。與我們共同成長(zhǎng),開啟 AI 新征程!立即行動(dòng),未來已來?。ㄔ斍檎?qǐng)戳:知識(shí)星球:ChatGPT&AI 變現(xiàn)圈,正式上線!)
掃碼加入:
