python修改json文件,如何使用Python更新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"}

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"}

How can I make that?

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

解决方案

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

You may also do this:

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值