【问题标题】:Python: Edit JSON item from FilePython:从文件编辑 JSON 项目
【发布时间】:2021-11-07 08:05:24
【问题描述】:

我有以下代码:

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 然后保存文件?

提前致谢! (另外,如果你不喜欢我的问题,至少告诉我我可以改进什么,我 13 岁,当人们不喜欢我的帖子而没有上下文时我不知道该怎么办)

【问题讨论】:

  • data["item"] = "text here"?

标签: python json python-3.x


【解决方案1】:

您所要做的就是分配给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)

【讨论】:

  • 我会测试这个:)
  • 工作,谢谢! :) Stack Overflow 将允许我在 1 分钟内接受答案... 编辑:接受
猜你喜欢
  • 2021-10-09
  • 1970-01-01
  • 2020-09-05
  • 2018-07-18
  • 2015-01-10
  • 2018-04-19
  • 2011-07-03
  • 2017-07-11
  • 1970-01-01
相关资源
最近更新 更多