繁体   English   中英

为什么在我的代码中 json pop 不起作用? (在蟒蛇中)

[英]Why does in my code json pop dont work? (In python)

让我解释一下我的问题!

我编写了一个 Python Discord Bot,它保存了频道 ID 和所有者 ID!

如果票被关闭,它需要弹出票!

我的代码看起来是这样的:

with open("data/tickets.json", "w") as f:
    data.pop(str(ctx.channel.id), f)

而json是这样的:

{
    "channel id 1": {
        "author": 256820568024,
        "claimed": null
    },
    "channel id 2": {
        "author": 43251524366254,
        "claimed": null
}

但如果我试图关闭票! 它删除了完整的tickets.json 文件! 好像里面什么都没有!

但我只想删除channel id 1部分。

它没有给我任何错误。

请帮助我:c

首先,您的 json 脚本缺少大括号。 它应该是:

{
    "channel id 1": {
        "author": 256820568024,
        "claimed": null
    },
    "channel id 2": {
        "author": 43251524366254,
        "claimed": null
    }
}

然后,您的代码旨在执行与您的初衷不同的事情。 请考虑JSON Python 模块。 这样,您将加载 json 对象,以便您可以随意操作数据!

import json

#read the file
data = json.load(open("data/tickets.json","r"))

#remove the object
del (data[str(ctx.channel.id)])

#if necessary, update the file
with open('data/tickets.json', 'w') as file:
    json.dump(data,file,indent=4)

希望能帮助到你!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM