How to update a JSON file by using Python?

只谈情不闲聊 提交于 2019-12-03 07:35:33

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.

You are almost there, you only have to write the updated json_data back to the file. Get rid of f.close(), as the with statement will ensure that the file is closed. Then, issue

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

This is simplest way to do the json file updation/writing. where you are creating instance of json file as 'f' and the writing the 'data' into the json file,

#write json file

with open('data.json', 'w') as f:
    json.dump(data, f)

#Read json file

with open('data.json', 'r') as f:
    json.load(data, f)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!