Python json讀寫方式和字典相互轉化
阿新 • • 發佈:2020-04-20
在Python中,json指的是符合json語法格式的字串,可以單行或者多行。
它可以方便的在使用在多種語言中,這裡介紹的是在python中的字典(dict)與json字串相互轉化的方式。
1. 匯入json包
import json
2. 初始化一個字典資料
dict_ = { 'name': 'Jack','age': 22,'skills': ['Python','Java','C++','Matlab'],'major': '計算機技術','english': '英語六級','school': 'WIT' }
3.json.dumps(字典):將字典轉為JSON字串
# 1. json.dumps(字典):將字典轉為JSON字串,indent為多行縮排空格數, # sort_keys為是否按鍵排序,ensure_ascii=False為不確保ascii,及不將中文等特殊字元轉為\uXXX等 json_dict = json.dumps(dict_) print(json_dict)
很明顯中文字元被轉化了,於是使用:ensure_ascii=False
# 行縮排和鍵值排序 json_dict_2 = json.dumps(dict_,indent=2,sort_keys=True,ensure_ascii=False) print(json_dict_2)
3.json.loads(json串),將json字串轉化成字典
dict_from_str = json.loads(json_dict) print(dict_from_str) dict_from_str_2 = json.loads(json_dict_2) print(dict_from_str_2)
4.json.dump,把字典轉換成json字串並存儲在檔案中,結果檔案如下圖:
with open("write_json.json","w",encoding='utf-8') as f: # json.dump(dict_,f) # 寫為一行 json.dump(dict_,f,ensure_ascii=False) # 寫為多行
5.json.load,從檔案開啟json資料轉換成字典
with open("write_json.json",encoding="utf-8") as f: json_file = json.load(f) print(json_file)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。