dumps是將dict轉化成json字符串格式,loads是將json字符串轉化成dict格式。
dump和load也是類似的功能,只是與文件操作結合起來了。
dump(寫入內容,文件對象) 和load(文件對象)
代碼實現:
def write_file():
like_num = input('請輸入您喜歡的數字:')
with open('C:\\Users\\Administrator\\Desktop\\data.json','w') as fw:
json.dump(like_num,fw) # 將內容寫入文件
with open('C:\\Users\\Administrator\\Desktop\\data.json','r') as fr:
data = json.load(fr) # 讀取文件內容
return data
data = write_file()
print("I know your favorite number! It's {}.".format(data))
dumps() 和loads()
data = {'key1':1,'key2':2}
print(json.dumps(data)) #{"key1": 1, "key2": 2}
print(json.loads(json.dumps(data))) #{'key1': 1, 'key2': 2}