什么是JSON?
JSON 的全稱(chēng)是 JavaScript Object Notation,即 JavaScript 對(duì)象符號(hào),它是一種輕量級(jí)、跨平臺(tái)、跨語(yǔ)言的數(shù)據(jù)交換格式,其設(shè)計(jì)意圖是把所有事情都用設(shè)計(jì)的字符串來(lái)表示,這樣既方便在互聯(lián)網(wǎng)上傳遞信息,也方便人進(jìn)行閱讀。
JSON 主要有兩種數(shù)據(jù)結(jié)構(gòu):
當(dāng)程序把 JSON 對(duì)象或 JSON 字符串轉(zhuǎn)換成 Python 對(duì)象時(shí),從 JSON 類(lèi)型到 Python 類(lèi)型的轉(zhuǎn)換關(guān)系如下所示:
JSON類(lèi)型Python類(lèi)型JSON 類(lèi)型Python 類(lèi)型對(duì)象(object)字典(dict)數(shù)組(array列表(list)字符串(string)字符串(str)整數(shù)(number(int))整數(shù)(int)實(shí)數(shù)(number(real))浮點(diǎn)數(shù)(float)trueTruefalseFalsenullNone
同樣的,當(dāng)程序把 Python 對(duì)象轉(zhuǎn)換成 JSON 格式字符串時(shí),從 Python 類(lèi)型到 JSON 類(lèi)型的轉(zhuǎn)換關(guān)系如下所示:
Python類(lèi)型JSON類(lèi)型Python 類(lèi)型JSON 類(lèi)型字典(dict)對(duì)象(object)列表(list)和元組(tuple)數(shù)組(array)字符串(str)字符串(string)整型、浮點(diǎn)數(shù),枚舉數(shù)值型(number)TruetrueFalsefalseNonenull
Python3 中可以使用 json 模塊來(lái)對(duì) JSON 數(shù)據(jù)進(jìn)行編解碼,它包含了兩個(gè)函數(shù):
== 使用dumps函數(shù)對(duì)數(shù)據(jù)進(jìn)行編碼==
import json # 創(chuàng)建字典類(lèi)型Person person = { 'name': '知秋小夢(mèng)', 'gender': 'male', 'age': 18 } # Python字典類(lèi)型轉(zhuǎn)換為JSON對(duì)象 json_person = json.dumps(person) print(json_person) # 輸出 {"name": "\u77e5\u79cb\u5c0f\u68a6", "gender": "male", "age": 18}
輸出的中文是中文的ascii字符碼,而不是真正的中文。
這是因?yàn)閖son.dumps 序列化時(shí)對(duì)中文默認(rèn)使用的ascii編碼
因此需要使用ensure_ascii=False來(lái)指定出中文
# 設(shè)置不適用ascll編碼 json_person = json.dumps(person,ensure_ascii=False) print(json_person) # 輸出 {"name": "知秋小夢(mèng)", "gender": "male", "age": 18}
== 使用loads函數(shù)對(duì)數(shù)據(jù)進(jìn)行解碼 ==
# 將 JSON 對(duì)象轉(zhuǎn)換為 Python 字典 dict_person = json.loads(json_person) print("person['name']: ",dict_person['name']) print("person['age']: ", dict_person['age']) # 輸出 person['name']: 知秋小夢(mèng) person['age']: 18
dumps()和loads()主要用于Python和json對(duì)象的相互轉(zhuǎn)化,dump()與load()主要用于讀寫(xiě)json文件
# 寫(xiě)入 JSON 數(shù)據(jù) with open('data.json', 'w', encoding='utf-8') as f: json.dump(data, f) # 讀取 JSON 數(shù)據(jù) with open('data.json', 'r', encoding='utf-8') as f: data = json.load(f)
JSON作為數(shù)據(jù)存儲(chǔ)、交互用的比較多,比如網(wǎng)頁(yè)cookie、數(shù)據(jù)交互等,建議掌握!
當(dāng)前名稱(chēng):Python入門(mén)進(jìn)階教程-JSON操作-創(chuàng)新互聯(lián)
標(biāo)題URL:http://chinadenli.net/article24/dsdhje.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站維護(hù)、自適應(yīng)網(wǎng)站、網(wǎng)站排名、響應(yīng)式網(wǎng)站、網(wǎng)站策劃、面包屑導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容