dump
json.dump()用於將dict類型的數據轉成str,並寫入到json文件中。
import json Dict = {"name":"tom"} with open("./file.json", "w") as f: json.dump(Dict, f)
load
json.load()用於從json文件中讀取數據
import json with open("./file.json", "r") as f: Dict = json.load(f) print(Dict)
dumps
json.dumps()用於將dict類型的數據轉成str,因為如果直接將dict類型的數據寫入json文件中會發生報錯,因此在將數據寫入時需要用到該函數。
import json Dict = {"name": "tom"} Str = json.dumps(Dict) with open("./file.json", "w") as f: f.write(Str)
json序列化時,默認遇到中文會轉換成unicode,如果想要保留中文在序列化時,在dumps函數中添加參數ensure_ascii=False即可解決。
loads
json.loads()用於將str類型的數據轉成dict。
import json Dict = {"name": "tom"} Str = json.dumps(Dict) Dict1 = json.loads(Str)