繁体   English   中英

在Python中将值添加到JSON对象

[英]Add values to JSON object in 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库加载数据,然后将字段添加到“事故”数组中的对象。 我已经像这样加载了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:关键字不能是表达式

我尝试了许多不同的方法。 如何使用Python将数据添加到JSON对象?

首先, accidents是一本字典,您不能write字典。 您只需在其中设置值。

因此,您想要的是:

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

write是新的JSON,在完成数据修改后,可以dumpdump回文件。

理想情况下,您可以通过写入新文件,然后将其移到原始文件上来完成此操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM