大資料實戰(八十七):電商數倉(七十一)安全之Sentry許可權管理
阿新 • • 發佈:2020-08-28
json是種通用資料型別 ,json就是字串,所有語言都可以解析
{ "name": "xiaohei", "cars": [ 1, 2, 3 ], "house": [ 4, 5, 6 ], "tt": "哈哈" }
python中json和dict可以互轉
由json轉dict用loads,eg:
import json #json只有雙引號 json_str ='{"name": "xiaohei", "cars":"bmw"}' dic1= json.loads(json_str) print(dic1)
由dict轉json用dumps,eg:
import json #json只有雙引號 d = { 'name':'xiaohei', 'cars':[1,2,3], 'house':(4,5,6), 'tt':'哈哈' } result = json.dumps(d,indent=4,ensure_ascii=False)#python轉json的(list、tuple、dict) print(result) print(type(result))
將檔案中的json讀出來成字典用load
info.txt:
import json
with open('info.txt',encoding='utf-8') as fr: re = json.load(fr)#簡化了寫和轉字典 print(re) print(type(re))
#與前面相同功能 res = fr.read() re = json.loads(res) print(re) print(type(re))
將字典轉成json存入檔案中用dump
import json
d = {
'name':'xiaohei',
'cars':[1,2,3],'house':(4,5,6),
'tt':'哈哈'
}
#轉成字串寫入檔案 with open('info.json','w',encoding='utf-8') as fw: json.dump(d,fw,indent=4,ensure_ascii=False)#等同下兩行 # result = json.dumps(d, indent=4, ensure_ascii=False) # fw.write(result)