首页 > 解决方案 > 更新 JSON 文件的键值

问题描述

我有一个 json 文件

{
    "id_1" : "",
    "id_2": ""
}

我正在尝试使用以下函数更新每个值

    async def UpdateID(self):
        await self.bot.wait_until_ready()
        while not self.bot.is_closed():
            id1 = 1
            id2 = 2
            with open("file.json", "r+") as r:
                config_json = json.load(r)
                config_json.update({"id_1": "%s" %(id1)})
                config_json.update({"id_2": "%s" %(id2)})
                json.dump(config_json,r)
            await asyncio.sleep(120)

使用 mode r+,它复制文件并将其添加到末尾,从而复制所有数据而不是替换。如果我使用r,我不能写。

如果我使用wor a,我会在步骤中收到UnsupportedOperation,not readable错误。json.load使用w也会使文件为空。

a+ and w+,在步骤上给出一个JSONDecodeError,Expecting value: line 1 column 1 (char 0)错误。json.load

我使用了错误的模式,还是解决原始问题的方法不正确?

标签: pythonjson

解决方案


你可以这样做

import json

async def updateId(self):
    do_something()

    with open(file_name) as f:
        config = json.load(f)

    update_your_config()

    with open(file_name, 'w') as f:
         json.dumps(config, f)

    do_something()


推荐阅读