python 處理json
阿新 • • 發佈:2022-01-08
1、dumps:將python中的 字典 轉換為 字串
import json
test_dict = {'bigberg': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt', 300]]}]}
print(test_dict)
print(type(test_dict))
#dumps 將資料轉換成字串
json_str = json.dumps(test_dict)
print(json_str)
print(type(json_str))
2、loads: 將 字串 轉換為 字典
new_dict = json.loads(json_str) print(new_dict) print(type(new_dict))
3、dump: 將資料寫入json檔案中
with open("../config/record.json","w") as f:
json.dump(new_dict,f)
print("載入入檔案完成...")
4、load:把檔案開啟,並把字串變換為資料型別
with open("../config/record.json",'r') as load_f: load_dict = json.load(load_f) print(load_dict) load_dict['smallberg'] = [8200,{1:[['Python',81],['shirt',300]]}] print(load_dict) with open("../config/record.json","w") as dump_f: json.dump(load_dict,dump_f)
5、遍歷key value
test_json = {"a":1,"b":2,"c":3}
for key,value in test_json.items():
print key,value