Python模組之json

米蘭的小鐵匠_feng發表於2019-02-18
  • json.dumps(), json.dump(), json.loads(), json.load()

dump的功能就是把Python物件encode為json物件,一個編碼過程。注意json模組提供了json.dumpsjson.dump方法,區別是dump直接到檔案,而dumps到一個字串。json.loads從json物件decode解碼為Python可以識別的物件,json.load可以直接load檔案:

import json

dic = {`name`: `alex`} 
dic_str = json.dumps(dic)
print(dic_str)   # {"name": "alex"}
print(type(dic_str)).   # <class `str`>

dic_loads = json.loads(dic_str)
print(dic_loads)  # {`name`: `alex`}
print(type(dic_loads))  # <class `dict`>

f_write = open(`new_file`, `w`)
a = json.dump(dic, f_write)  #把Python物件編碼為string,並寫入檔案
f_write.close()

f_read = open(`new_file`, `r`)
data = f_read.read()
print(data)  #{"name": "alex"}
f_read.close()

f_load = open(`new_file`, `r`)
load_data = json.load(f_load)
print(load_data)  # {`name`: `alex`}
print(type(load_data))  # <class `dict`>
f_load.close()

 

相關文章