从文件编辑 JSON 项目

问题描述 投票:0回答:1

我有以下代码:

import json
with open("prefix.json", 'r+') as f:
    data = json.load(f)
def changeprefix(id, prefix):
    global data
    if not id in data:
        json.dump(data, open("prefix.json", "w"), indent = 4)
        data[id] = prefix
    else:
        // Code to edit existing item
changeprefix("6", "?")

它会打开一个名为

prefix.json
的文件,我希望能够编辑现有项目,例如:

(Example.json)
{
    "item": "234"
}
 

如何将

item
更改为 py 中的其他内容,例如更改为
text here
然后保存文件?

python json python-3.x
1个回答
2
投票

您所要做的就是分配给

data["item"]
,然后将所有
data
写入
prefix.json

data["item"] = "text here"
with open("prefix.json", "w") as f: # Makes sure to close the file
    json.dump(data, f, indent=4)
© www.soinside.com 2019 - 2024. All rights reserved.