Python Json數(shù)據(jù)文件操作原理解析
引言
接口測(cè)試就是數(shù)據(jù)的測(cè)試,在測(cè)試之前,需要準(zhǔn)備好測(cè)試數(shù)據(jù),而測(cè)試數(shù)據(jù)可以用數(shù)據(jù)庫(kù)、excel、txt和csv方式,當(dāng)然還有一種方式,那就是使用json文件來(lái)儲(chǔ)存測(cè)試數(shù)據(jù)。常用的方式就是這些。
設(shè)計(jì)思路
python讀取json文件和讀取txt方式是一樣的,獲取路徑,判斷路徑是否存在,獲取文件名及絕對(duì)路徑,打開讀取數(shù)據(jù),提取關(guān)鍵數(shù)據(jù),關(guān)閉文件。具體流程,畫了一個(gè)草圖方便理解:
具體代碼實(shí)現(xiàn)
@author: Leo @software: pycharm @file: operate_json.py @time: 2020/5/3 0003 9:01 @Desc: ’’’__author__ = ’Leo’ import osimport json # 獲取當(dāng)前文件所在的絕對(duì)路徑curPath = os.path.abspath(os.path.dirname(__file__))print(curPath)rootPath = os.path.abspath(os.path.dirname(curPath))print(rootPath) config_file_name = r’./data/api_json’ class OperateJson(object): ''' 操作Json文件 ''' def __init__(self,file_name = None): if file_name: self.file_name = file_name else: self.get_file = config_file_name self.file_name = os.path.join(rootPath,self.get_file) print('文件名稱:%s'%self.file_name) self.data = self.read_json() def read_json(self): ''' 讀取json數(shù)據(jù) ''' with open(self.file_name,encoding=’utf8’) as fp: # 反序列化,從文件讀取(string轉(zhuǎn)dict) data = json.load(fp) fp.close() return data def get_keyword_data(self,key): ''' 讀取關(guān)鍵字 ''' return self.data[key]if __name__ == ’__main__’: # oj = OperateJson('../data/package.json') oj = OperateJson() print(oj.read_json()) print(oj.get_keyword_data(’api1’)) print(oj.get_keyword_data(’api1’)[’url’]) print(oj.get_keyword_data(’api1’)[’data’])
運(yùn)行結(jié)果:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python實(shí)現(xiàn)讀取類別頻數(shù)數(shù)據(jù)畫水平條形圖案例2. python中PyQuery庫(kù)用法分享3. python操作數(shù)據(jù)庫(kù)獲取結(jié)果之fetchone和fetchall的區(qū)別說(shuō)明4. Ajax實(shí)現(xiàn)頁(yè)面無(wú)刷新留言效果5. php5.6不能擴(kuò)展redis.so的解決方法6. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能7. 阿里前端開發(fā)中的規(guī)范要求8. 關(guān)于HTML5的img標(biāo)簽9. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫特效10. PHP獲取時(shí)間戳等相關(guān)函數(shù)匯總
