在Python中向JSON对象添加值

2024-06-13 10:46:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有效的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不能是表达式

我试过很多不同的方法。如何使用Python向JSON对象添加数据?


Tags: 数据对象jsoncitydata自行车stsan
1条回答
网友
1楼 · 发布于 2024-06-13 10:46:05

首先,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

相关问题 更多 >