python - 在 Python 中向 JSON 对象添加值

标签 python json

我有一个有效的 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/

相关文章:

python - 正则表达式类似于 Python 中的赫斯特模式

python - Matplotlib 轴 : splitting an axes object into two

python - "== True"和 "is True"的表达式给出不同的结果

mysql - 我想制作json数据

ios - 如何使用本地数据加载应用程序并随后在线时更新它。

c++ - boost json_parser 警告 C4715

c# - 如何使用 Json.NET 序列化和反序列化数组的 ArrayList

python - 如果多个列值相同(或为空),则选择行

Python numpy 性能 - 在非常大的数组上选择

javascript - Ajax显示数组中的json数据