2014-11-03 94 views
1

我有一個有效的JSON對象,與多家電動自行車事故中列出:添加值JSON對象在Python

{ 
    "city":"San Francisco", 
    "accidents":[ 
     { 
     "lat":37.7726483, 
     "severity":"u'INJURY", 
     "street1":"11th St", 
     "street2":"Kissling St", 
     "image_id":0, 
     "year":"2012", 
     "date":"u'20120409", 
     "lng":-122.4150145 
     }, 

    ], 
    "source":"http://sf-police.org/" 
} 

我試圖使用JSON庫在python加載數據和然後將字段添加到「意外」數組中的對象。我裝我的JSON像這樣:

with open('sanfrancisco_crashes_cp.json', 'rw') as json_data: 
    json_data = json.load(json_data) 
    accidents = json_data['accidents'] 

當我嘗試寫入文件,像這樣:

for accident in accidents: 
    turn = randTurn() 
    accidents.write(accident['Turn'] = 'right') 

我得到以下錯誤:語法錯誤:關鍵字不能表達

我試過了很多不同的方法。如何使用Python將數據添加到JSON對象?

+0

作爲一個側面說明,「JSON對象」是一個非常令人困惑的術語。您已經獲得了JSON解碼/編碼的Python字典,並且您已經獲得了編碼爲的文本字符串,並且當您說「JSON對象」時,您說的是哪一個都是不明確的。最好清楚你的意思。 – abarnert 2014-11-03 20:34:52

回答

4

首先,accidents是一本字典,而你不能將write轉換成字典;你只需在其中設置值。

所以,你想要的是:

for accident in accidents: 
    accident['Turn'] = 'right' 

write出來的東西是新的JSON-後,你已經完成修改數據時,可以dump迴文件。

理想情況下,你通過寫一個新的文件,然後移動它在原來的做到這一點:

with open('sanfrancisco_crashes_cp.json') as json_file: 
    json_data = json.load(json_file) 
accidents = json_data['accidents'] 
for accident in accidents: 
    accident['Turn'] = 'right' 
with tempfile.NamedTemporaryFile(dir='.', delete=False) as temp_file: 
    json.dump(temp_file, json_data) 
os.replace(temp_file.name, 'sanfrancisco_crashes_cp.json') 

但是你可以就地做,如果你真的想:

# notice r+, not rw, and notice that we have to keep the file open 
# by moving everything into the with statement 
with open('sanfrancisco_crashes_cp.json', 'r+') as json_file: 
    json_data = json.load(json_file) 
    accidents = json_data['accidents'] 
    for accident in accidents: 
     accident['Turn'] = 'right' 
    # And we also have to move back to the start of the file to overwrite 
    json_file.seek(0, 0) 
    json.dump(json_file, json_data) 
    json_file.truncate() 

如果你想知道爲什麼你得到了你所做的具體錯誤:

Python-與許多其他語言不同 - 作爲簽名不是表達式,它們是陳述,必須由他們自己完成。

但是函數調用中的關鍵字參數的語法非常相似。例如,請參閱上面示例代碼中的tempfile.NamedTemporaryFile(dir='.', delete=False)

因此,Python試圖解釋您的accident['Turn'] = 'right'就好像它是一個關鍵字參數,關鍵字accident['Turn']。但關鍵字只能是實際的單詞(以及標識符),而不是任意的表達式。所以它試圖解釋你的代碼失敗,並且你得到一個錯誤,說keyword can't be an expression