简体   繁体   English

在Python中将值添加到JSON对象

[英]Add values to JSON object in Python

I've got a valid JSON object, with a number of bike accidents listed: 我有一个有效的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/"
}

I'm trying to use the json library in python to load the data and then add fields to the objects in the "accidents" array. 我正在尝试在python中使用json库加载数据,然后将字段添加到“事故”数组中的对象。 I've loaded my json like so: 我已经像这样加载了json:

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

When I try to write to the file like so: 当我尝试像这样写入文件时:

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

I get the following error: SyntaxError: keyword can't be an expression 我收到以下错误:SyntaxError:关键字不能是表达式

I've tried a number of different ways. 我尝试了许多不同的方法。 How can you add data to a JSON object using Python? 如何使用Python将数据添加到JSON对象?

First, accidents is a dictionary, and you can't write to a dictionary; 首先, accidents是一本字典,您不能write字典。 you just set values in it. 您只需在其中设置值。

So, what you want is: 因此,您想要的是:

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

The thing you want to write out is the new JSON—after you've finished modifying the data, you can dump it back to a file. write是新的JSON,在完成数据修改后,可以dumpdump回文件。

Ideally you do this by writing to a new file, then moving it over the original: 理想情况下,您可以通过写入新文件,然后将其移到原始文件上来完成此操作:

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')

But you can do it in-place if you really want to: 但是,如果您确实希望:

# 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()

If you're wondering why you got the specific error you did: 如果您想知道为什么会遇到特定错误,请执行以下操作:

In Python—unlike many other languages—assignments aren't expressions, they're statements, which have to go on a line all by themselves. 在Python中,与许多其他语言不同,赋值不是表达式,而是语句,它们必须自己一行。

But keyword arguments inside a function call have a very similar syntax. 但是函数调用中的关键字参数具有非常相似的语法。 For example, see that tempfile.NamedTemporaryFile(dir='.', delete=False) in my example code above. 例如,在我上面的示例代码中看到tempfile.NamedTemporaryFile(dir='.', delete=False)

So, Python is trying to interpret your accident['Turn'] = 'right' as if it were a keyword argument, with the keyword accident['Turn'] . 因此,Python试图将您的accident['Turn'] = 'right'为带有关键词accident['Turn']的关键字参数。 But keywords can only be actual words (well, identifiers), not arbitrary expressions. 但是关键字只能是实际单词(嘛,标识符),不能是任意表达式。 So its attempt to interpret your code fails, and you get an error saying keyword can't be an expression . 因此,它尝试解释您的代码的尝试失败,并且您收到一条错误消息,指出keyword can't be an expression

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

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