- json.dumps()蝎抽,用于數(shù)據(jù)類(lèi)型的轉(zhuǎn)換
json.dumps()用于將dict類(lèi)型的數(shù)據(jù)轉(zhuǎn)成str政钟,因?yàn)槿绻苯訉ict類(lèi)型的數(shù)據(jù)寫(xiě)入json文件中會(huì)發(fā)生報(bào)錯(cuò),因此在將數(shù)據(jù)寫(xiě)入時(shí)需要用到該函數(shù)樟结。
import json
test1_dict = {'NAME': 'sw', 'phone': '10086'}
print(test1_dict)
print('json.dumps轉(zhuǎn)換前的類(lèi)型是:', type(test1_dict))
test1_str = json.dumps(test1_dict)
print(test1_str)
print('json.dumps轉(zhuǎn)換后的類(lèi)型是:', type(test1_str))
執(zhí)行結(jié)果如下:- json.loads()养交,用于數(shù)據(jù)類(lèi)型的轉(zhuǎn)換
json.loads()用于將str類(lèi)型的數(shù)據(jù)轉(zhuǎn)成dict,因?yàn)槿绻老x(chóng)解碼孩子后得到的是網(wǎng)頁(yè)的字符串瓢宦,不轉(zhuǎn)換成python類(lèi)型的數(shù)據(jù)碎连,無(wú)法進(jìn)行數(shù)據(jù)提取。
import json
test1_dict = {'NAME': 'sw', 'phone': '10086'}
print(test1_dict)
print('json.dumps轉(zhuǎn)換前的類(lèi)型是:', type(test1_dict))
test1_str = json.dumps(test1_dict)
print(test1_str)
print('json.dumps轉(zhuǎn)換后的類(lèi)型是:', type(test1_str))
test2_dict = json.loads(test1_str)
print(test2_dict)
print('json.loads轉(zhuǎn)換后的類(lèi)型是:', type(test2_dict))
執(zhí)行結(jié)果如下:- json.dump(),跟文件結(jié)合一起使用
json.dump()需要兩個(gè)參數(shù)驮履,沒(méi)有返回值鱼辙,多與“w”連用,用于將dict類(lèi)型的數(shù)據(jù)轉(zhuǎn)成str疲吸,并寫(xiě)入到j(luò)son文件中座每。它在底層做了兩件事,一件事是將對(duì)象(列表)轉(zhuǎn)換為字符串摘悴,第二件事是轉(zhuǎn)換成功以后峭梳,將轉(zhuǎn)換后的數(shù)據(jù)寫(xiě)入到文件中。
import json
test1_dict = {'NAME': 'sw', 'phone': '10086'}
print(test1_dict)
print('test1_dict的類(lèi)型是:', type(test1_dict))
with open('text1.txt', 'w') as f:
json.dump(test1_dict, f)
執(zhí)行結(jié)果得到一個(gè)text1.txt文件。- json.load(),跟文件結(jié)合一起使用
json.load()用于從json文件中讀取數(shù)據(jù)葱椭。與讀 "r"連用多捂寿,可讀出文件的內(nèi)容,并打印出來(lái)孵运。
import json
test1_dict = {'NAME': 'sw', 'phone': '10086'}
print('test1_dict的類(lèi)型是:', type(test1_dict))
with open('text1.txt', 'w') as f:
json.dump(test1_dict, f)
f.closed
with open('text1.txt', 'r') as f:
test1_str = json.load(f)
print(test1_str)
執(zhí)行結(jié)果打印出來(lái)text1.txt中的內(nèi)容秦陋。總結(jié)
json.loads()、json.dumps():就是用來(lái)進(jìn)行數(shù)據(jù)類(lèi)型的轉(zhuǎn)換治笨。
json.load()驳概、json.dump():只能跟文件結(jié)合一起使用。