python: json庫 & .json檔案讀寫
阿新 • • 發佈:2019-01-28
API
API | Annotation |
---|---|
json.dumps( ) | 將python中的 字典 轉換為 字串 |
json.loads( ) | 將 字串 轉換為 字典 |
json.dump( , ) | 將資料寫入json檔案中 |
json.load( ) | 把檔案開啟,並把字串變換為資料型別 |
Note:
- 如果要將 字串 轉換為 list ,則直接
list()
之即可,不必呼叫json庫。
中文讀寫
json.dump(dict_1, dump_f, ensure_ascii=False, indent=4)
- ensure_ascii=False:輸出原有的語言文字,可通過該引數實現中文寫入。
- indent:縮排量,一般省略。
Test
import json
dict_1 = {"City":"Nanjing", "Year":2018, "Province":"Jiangshu"}
# dumps:將python中的 字典 轉換為 字串
str_1 = json.dumps(dict_1)
assert isinstance(str_1, str)
# loads: 將 字串 轉換為 字典
dict_2 = json.loads(str_1)
assert isinstance(dict_2, dict)
# dump: 將資料寫入json檔案中
with open("./test.json", "w") as dump_f:
json.dump(dict_1, dump_f, ensure_ascii=False, indent=4)
# load:把檔案開啟,並把字串變換為資料型別
with open("./test.json", "r") as load_f:
dict_3 = json.load(load_f)
assert isinstance(dict_3, dict)