【问题标题】:How to add to JSON value on external file?如何在外部文件中添加 JSON 值?
【发布时间】:2021-07-12 18:10:13
【问题描述】:

我想看看是否可以使用 python 更新外部 JSON 文件上的值。

我的 JSON 文件,名为 inventory.json

{
    "sword": 1,
    "shield": 0,
    "key": 0
}

是否可以使用命令,例如:

data["shield"] += 1
data["shield"] += 7

将剑的 JSON 文件的值更新一,使文件看起来像这样?

{
    "sword": 2,
    "shield": 7,
    "key": 0
}

【问题讨论】:

  • 将 JSON 读入 dict,递增值,将其写回文件。
  • 是的。将 JSON 文件读入字典,更新字典并转储回文件。我会让你弄清楚细节。提示:有一个名为json 的库。
  • 读取json,更新值,写回文件
  • 我没有downvote your question because no attempt was made,因为您是一个相对较新的贡献者,但通常我们希望您提供honest attempt at the solution,然后然后提出具体问题) 关于您的实施。

标签: python json python-3.x


【解决方案1】:

其他评论完全正确。这个问题的一个很好的解决方案是导入 json 库,在代码顶部使用 import json。然后,您可以使用:

json_file = open("file.json", "r")
json_text = json_file.read()
json_file.close()
json_dict = json.loads(json_text)

在此之后,您将拥有 JSON 字典对象“json_dict”。您可以通过键修改此字典中的值,例如json_dict['sword']+=3json_dict['name'] = "Marc"。完成所有想要进行的修改后,可以将 JSON dict 写入文件。

writing_file = open("file.json","w")
writing_file.write(json.dumps(json_dict))
writing_file.close()

如果您愿意,您可以通过将最后三行放在只接受 dict 的函数中来将其作为更新 JSON 文件的函数来执行。 json.loads() 接受一个 json 格式的字符串并将其转换为 Python 字典,json.dumps() 接受一个 Python 字典并将其转换为 json 格式的字符串。

一般来说,通过将值用作变量(json_dict)将值保存在内存中比不断地读写文件要好,因为你不能只跳转到'sword'索引文件,你必须搜索它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-23
    • 2018-02-11
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多