新聞中心

JSON模塊
JSON (JavaScript Object Notation):是一個輕量級的數(shù)據(jù)交換格式模塊,受javascript對象文本語法啟發(fā),但不屬于JavaScript的子集。
常用方法:
dump(obj,fp):將對象以字符串的形式寫入文件中。
load(fp):將數(shù)據(jù)從文件中讀出,并返回(需要變量接收)數(shù)據(jù)的原類型。
dumps(obj):將對象轉(zhuǎn)換成json字符串形式。
loads(str):將json字符串?dāng)?shù)據(jù)轉(zhuǎn)換成原來的數(shù)據(jù)類型。
相關(guān)推薦:《python視頻教程》
實(shí)例如下:dumps(obj) | loads(str)
import json
dict_1 = {"電影":"黃飛鴻","電視劇":"霍元甲"}
json_str = json.dumps(dict_1) # 將字典轉(zhuǎn)換成json的字符串類型
dict_2 = json.loads(json_str) # 將json的字符串類型轉(zhuǎn)換成原數(shù)據(jù)
print(json_str,type(json_str))
print(dict_2.items(),type(dict_2))打印內(nèi)容如下
{"\u7535\u5f71": "\u9ec4\u98de\u9e3f", "\u7535\u89c6\u5267": "\u970d\u5143\u7532"}
dict_items([('電影', '黃飛鴻'), ('電視劇', '霍元甲')]) 實(shí)例如下:dump(obj,fp) | load(fp)
import json
# 向文件中寫入json數(shù)據(jù)
dict_1 = {"電影":"黃飛鴻","電視劇":"霍元甲"}
file_write = open("json.txt",mode="w",encoding="utf-8")
json.dump(dict_1,file_write) # 將字典以json的字符串類型寫入文件
file_write.close()從文件中讀取json數(shù)據(jù)
file_read = open("json.txt",mode="r",encoding="utf-8")
dict_2 = json.load(file_read) # 將文件中內(nèi)容轉(zhuǎn)換成原數(shù)據(jù)類型并返回
file_read.close()
print(dict_2.items(),type(dict_2)) # 打印轉(zhuǎn)換后的數(shù)據(jù)打印內(nèi)容如下
dict_items([('電影', '黃飛鴻'), ('電視劇', '霍元甲')]) 這里需要注意的是json模塊dump(obj,fp)雖然可以多次上傳,但是在load時(shí)會報(bào)錯,load(fp)函數(shù)不能轉(zhuǎn)換多次dump的數(shù)據(jù)。所以如果想要向json文件中新增數(shù)據(jù)時(shí),需要將數(shù)據(jù)load下來轉(zhuǎn)換成原數(shù)據(jù),然后在原數(shù)據(jù)基礎(chǔ)上進(jìn)行新增。最后將處理后的數(shù)據(jù)dump覆蓋寫到文件中。
文章名稱:創(chuàng)新互聯(lián)Python教程:一文帶你讀懂JSON模塊
網(wǎng)頁路徑:http://m.fisionsoft.com.cn/article/coegojp.html


咨詢
建站咨詢
