如何使用Python更新JSON文件? [英] How to update a JSON file by using Python?

查看:770
本文介绍了如何使用Python更新JSON文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python,并且有一个JSON文件,我想在其中更新与给定键相关的值.也就是说,我的my_file.json包含以下数据

I am using Python and I have a JSON file in which I would like to update a value related to a given key. That is, I have the my_file.json containing the following data

{"a": "1", "b": "2", "c": "3"}

,我只想将与b键相关的值从2更改为9,以便更新后的文件如下所示:

and I would like to just change the value related to the b key from 2 to 9 so that the updated file look as like:

{"a": "1", "b": "9", "c": "3"}

我该怎么做?

我尝试了以下操作,但没有成功(更改未保存到文件中):

I tried the following but without success (the changes are not saved to the file):

with open('my_file.json', 'r+') as f:
    json_data = json.load(f)
    json_data['b'] = "9"
    f.close()

推荐答案

您根本没有保存更改的数据.您必须先加载,然后修改,然后再保存.无法就地修改JSON文件.

You did not save the changed data at all. You have to first load, then modify, and only then save. It is not possible to modify JSON files in-place.

with open('my_file.json', 'r') as f:
    json_data = json.load(f)
    json_data['b'] = "9"

with open('my_file.json', 'w') as f
    f.write(json.dumps(json_data))

您也可以这样做:

with open('my_file.json', 'r+') as f:
    json_data = json.load(f)
    json_data['b'] = "9"
    f.seek(0)
    f.write(json.dumps(json_data))
    f.truncate()

如果要确保安全,请先将新数据写入同一文件夹中的临时文件,然后将该临时文件重命名为原始文件.这样一来,即使之间发生任何事情,您也不会丢失任何数据.

If you want to make it safe, you first write the new data into a temporary file in the same folder, and then rename the temporary file onto the original file. That way you will not lose any data even if something happens in between.

如果想到这一点,JSON数据就地更改非常困难,因为数据长度不是固定的,而且更改可能非常重要.

If you come to think of that, JSON data is very difficult to change in-place, as the data length is not fixed, and the changes may be quite significant.

这篇关于如何使用Python更新JSON文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆