- json.dumps(), json.dump(), json.loads(), json.load()
dump的功能就是把Python
物件encode
為json物件,一個編碼過程。注意json
模組提供了json.dumps
和json.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()