python之json文件讀寫操作的四種方法
python操作json的四種方法
python操作json文件通常有4中方法:
- json.loads
- json.load
- json.dumps
- json.dump
json.loads
將json對象轉(zhuǎn)化為python對象,也就是將字符串轉(zhuǎn)換為字典類型,例如:
import json
header = '{"Content-Type":"application/json","Authorization":"ww"}'
print(type(header))
newheader=json.loads(header)
print(type(newheader))

json.load
對json文件進行讀取
with open(dir_config.testcasedir+"/allVersion.json") as f:
allversion=json.load(f)
print(type(allversion))
也可以通過json.loads讀取,但是需要把文件內(nèi)容轉(zhuǎn)換為二進制流,json.loads主要是對數(shù)據(jù)流進行轉(zhuǎn)換為json;而json.load主要是對文件進行轉(zhuǎn)換,二者的操作類型不一致,但是最終結(jié)果都是將其轉(zhuǎn)換為dict類型。
json.dumps
將python對象轉(zhuǎn)換為json對象,也就是將字典轉(zhuǎn)換為字符串:
import json
header = {"Content-Type":"application/json","Authorization":"ww"}
print(type(header))
newheader=json.dumps(header)
print(type(newheader))

json.dump
“編碼”,將數(shù)據(jù)寫入json文件
with open(dir_config.testcasedir+"/allVersion.json",'a') as f:
header = {"Content-Type":"application/json","Authorization":"ww"}
allversion=json.dump(header,fp=f)

到此這篇關(guān)于python之json文件讀寫操作的四種方法的文章就介紹到這了,更多相關(guān)python json文件讀寫操作內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python3 實現(xiàn)隨機生成一組不重復數(shù)并按行寫入文件
下面小編就為大家分享一篇Python3 實現(xiàn)隨機生成一組不重復數(shù)并按行寫入文件的示例。具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04
使用Python實現(xiàn)NBA球員數(shù)據(jù)查詢小程序功能
這篇文章主要介紹了使用Python實現(xiàn)NBA球員數(shù)據(jù)查詢小程序功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11

