python操作json的四種方法
python操作json文件通常有4中方法:
- json.loads
- json.load
- json.dumps
- json.dump
json.loads
將json對象轉化為python對象,也就是將字符串轉換為字典類型,例如:
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讀取,但是需要把文件內容轉換為二進制流,json.loads主要是對數(shù)據(jù)流進行轉換為json;而json.load主要是對文件進行轉換,二者的操作類型不一致,但是最終結果都是將其轉換為dict類型。
json.dumps
將python對象轉換為json對象,也就是將字典轉換為字符串:
import json
header = {"Content-Type":"application/json","Authorization":"ww"}
print(type(header))
newheader=json.dumps(header)
print(type(newheader))
json.dump
“編碼”,將數(shù)據(jù)寫入json文件文章來源:http://www.zghlxwxcb.cn/news/detail-688875.html
with open(dir_config.testcasedir+"/allVersion.json",'a') as f:
header = {"Content-Type":"application/json","Authorization":"ww"}
allversion=json.dump(header,fp=f)
文章來源地址http://www.zghlxwxcb.cn/news/detail-688875.html
到了這里,關于python之json文件讀寫操作的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!