在Python中向JSON对象添加值

3 投票
2 回答
25706 浏览
提问于 2025-05-01 09:41

我有一个有效的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对象里添加数据呢?

暂无标签

2 个回答

0

我用这个方法解决了:

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 open('sanfrancisco_crashes_cp.json', "w") as f:
        json.dump(json_data, f)
6

首先,accidents 是一个字典,而字典是不能直接“写入”的;你只能在里面设置值。

所以,你想要做的是:

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

撰写回答