我有一个有效的 JSON 对象,其中列出了一些自行车事故:
{
"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/"
}
我正在尝试使用 python 中的 json 库加载数据,然后将字段添加到“accidents”数组中的对象。我已经像这样加载了我的 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')
我收到以下错误:SyntaxError: keyword can't be an expression
我尝试了很多不同的方法。如何使用 Python 将数据添加到 JSON 对象?
最佳答案
首先,accidents
是一个字典,你不能write
到字典;您只需在其中设置值。
所以,你想要的是:
for accident in accidents:
accident['Turn'] = 'right'
您要写
的是新的 JSON — 完成数据修改后,您可以将其转储
回文件。
理想情况下,您可以写入一个新文件,然后将其移动到原始文件上:
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
。
关于python - 在 Python 中向 JSON 对象添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26722570/