2017-02-25 68 views
0

我正在嘗試創建一個文件並使用JSON將數據從變量寫入該新文件。目前,我有一個名爲open_diction的變量,它是包含其他數據的文件中的大型字典。所以我正在嘗試創建一個名爲open_diction_saved.json的新文件,並將open_diction中的數據寫入該新文件。目前我得到錯誤TypeError:不是JSON可序列化將數據從變量寫入字典

f = open ("open_diction_saved.json","w") 
json.dumps(f) 
f.write(open_diction) 
f.close() 

任何幫助將是偉大的!

回答

1

問題是你正試圖序列化一個可寫的文件對象。如果你的意圖是覆蓋open_diction_saved.json,那麼下面的代碼就是你要找的。

f = open("open_diction_saved.json", 'w') 

f.write(json.dumps(open_diction)) #serialise open_diction obj, then write to file 
f.close() 
+0

太好了!這工作感謝您的幫助和解釋! – Avery9115

0

您需要將json.dumps()寫()方法內:

import json 

open_diction = {'a':1, 'b':2} 

with open("open_diction_saved.json", "w") as f: 

    f.write(json.dumps(open_diction)) 
+0

非常感謝您的幫助,工作! – Avery9115