【问题标题】:How to update a JSON file by using Python?如何使用 Python 更新 JSON 文件?
【发布时间】:2014-08-26 02:57:57
【问题描述】:

我正在使用 Python,并且我有一个 JSON 文件,我想在其中更新与给定键相关的值。也就是说,我有 my_file.json 包含以下数据

{"a": "1", "b": "2", "c": "3"}

我只想将与b 键相关的值从2 更改为9,以便更新后的文件如下所示:

{"a": "1", "b": "9", "c": "3"}

我怎样才能做到这一点?


我尝试了以下但没有成功(更改未保存到文件中):

with open('my_file.json', 'r+') as f:
    json_data = json.load(f)
    json_data['b'] = "9"
    f.close()

【问题讨论】:

标签: python json file storage updating


【解决方案1】:

您根本没有保存更改的数据。您必须先加载,然后修改,然后才保存。无法就地修改 JSON 文件。

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

你也可以这样做:

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

如果要保证安全,请先将新数据写入同一文件夹中的临时文件,然后将临时文件重命名为原始文件。这样即使中间发生了一些事情,您也不会丢失任何数据。

如果您想到这一点,JSON 数据很难就地更改,因为数据长度不是固定的,而且更改可能相当大。

【讨论】:

  • 你能举个具体的例子吗?
  • 缺少冒号:第 5 行 - 第一个代码类别 with open('my_file.json', 'w') as f:
【解决方案2】:

您就快到了,您只需将更新后的json_data 写回文件即可。摆脱f.close(),因为with 语句将确保文件已关闭。然后,发出

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

【讨论】:

  • @DrV 点,另一个with 块可能比seek(0) 更干净
  • @timgeb: seek 也是一个不错的解决方案,看我的回答。
【解决方案3】:

这是进行 json 文件更新/写入的最简单方法。 您将 json 文件的实例创建为“f”并将“数据”写入 json 文件,

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

【讨论】:

    【解决方案4】:
    • 使用 json.load 函数打开文件并将所有内容存储在一个变量中

    • 更新存储在前一个变量中的密钥

    • 再次打开文件并使用变量 updated 更新您的内容

    def updateJsonFile():
        jsonFile = open("my_file.json", "r") # Open the JSON file for reading
        data = json.load(jsonFile) # Read the JSON into the buffer
        jsonFile.close() # Close the JSON file
    
        ## Working with buffered content
        data["b"] = "9"
    
        ## Save our changes to JSON file
        jsonFile = open("my_file.json", "w+")
        jsonFile.write(json.dump(data))
        jsonFile.close()
    

    【讨论】:

    • 不鼓励在 Stack Overflow 上发布纯代码帖子。通过添加支持信息和解释,您的答案可以得到很大改善。请参阅how to write a good answer 了解更多信息。
    猜你喜欢
    • 2012-12-06
    • 2016-06-22
    • 2022-01-19
    • 2015-08-11
    • 1970-01-01
    • 2016-09-26
    • 2015-04-17
    • 2014-09-05
    相关资源
    最近更新 更多