2014-11-03 93 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