2017-02-17 51 views
0

這可能是一個重複的問題,但是,我無法找到解決我自己的問題。我有這個名爲d.json的文件。它擁有ID和名稱,它是測試文件。如何添加到JSON值列表中?

{ 
    "id": [ 
     "1", 
     "2" 
    ], 
    "name": "p" 
} 

^這是當前的JSON。我需要能夠編輯該ID列表,但是,我已經試過這個解決方案:

>>> with open('d.json', 'r+') as f: 
     data = json.load(f) 
     r = data['id'].append("3") 
     f.write(r) 
     f.close() 

不過,我得到這個:

Traceback (most recent call last): 
    File "<pyshell#49>", line 4, in <module> 
    f.write(r) 
TypeError: write() argument must be str, not None 

整個想法是讓我能夠打開JSON文件,給列表添加一個快速值,關閉它,完成。

回答

3

在寫回文件之前,您需要將json轉換爲字符串。試試這個:

with open('d.json', 'r+') as f: 
    data = json.load(f) 
    data['id'].append("3") 
    f.seek(0) 
    json.dump(data, f) 
    f.truncate()