1. 程式人生 > 其它 >json yam 格式檔案操作

json yam 格式檔案操作

json格式資料和python資料的轉換

python 中的布林值:True False ----> 在json中的布林值 true false

python 中的空值:None ----> 在json中的空值 null

關於使用unittestreport中的json檔案資料做引數化處理:

第一步:from unittestreport import ddt ,json_data

第二步:在測試類上@ddt

第三步:在測試方法上面@json_data,傳入json資料檔案的路徑

第四步:在測試方法中定義一個引數,用於接收json_data傳遞過來的用例資料

注意:json檔案中的資料,要是陣列(列表)巢狀物件(字典)的格式

import json
# 1、將python中的資料轉換成json格式
li_python = [None,False,{'abc':12}]
li_json = json.dumps(li_python)
print(li_json)

# 2、將json格式資料轉換成python資料
li_json = '[null, false, {"abc": 12}]'
li_python = json.loads(li_json)
print(li_python)
# 3、載入json檔案,轉換為python對應的資料格式
with open(r'day0702\register_data.json
','r',encoding='utf8') as f: res = json.load(f) print(res) # 4、將python資料,寫入json檔案 with open(r'day0702\json_data.json','w') as f : json.dump(li_python,f)

yaml檔案格式:

檔案以 - 開頭是列表

頂格開始,代表是字典(注意字典後面冒號要空格)

yaml檔案的讀取:yaml.load 一個yaml檔案加載出來為一個字典物件,讀取出來就是字典

with open('yaml_test.yaml','r',encoding='utf8') as f:
print(yaml.load(f.read(),Loader=yaml.FullLoader))

yaml檔案的寫入:yaml.dump

import yaml
data = [1,'ba',None,False,{'age':10,'name':'萌萌'}]
with open('yaml_test.yaml','w',encoding='utf8') as f:
yaml.dump(data,f,allow_unicode=True)