Python中Json庫得dumps、loads、dump、load方法的使用
阿新 • • 發佈:2019-01-09
1. json.dumps()
json.dumps()用於將dict型別的資料轉成str型別,直接將dict型別的資料寫入json檔案中會發生異常,因此在將資料寫入時需要用到該函式。
2. json.loads()
json.loads()用於將str型別的資料轉成dict。
3. json.dump()
json.dump()用於將dict型別的資料轉成str,並寫入到json檔案中。有兩種方法寫入json檔案。
import json test_dict = {"name":"kobe","age":"38"} test_filename = (test.json) #method 1 test_str = json.dumps(test_dict) with open(test_filename,"w") as f: f.write(test_str) f.close() #method 2 test_str = json.dump(test_dict, open(test_filename, "w"))
4. json.load()
json.load()用於從json檔案中讀取資料。