简体   繁体   English

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

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

Let me explain my problem!让我解释一下我的问题!

I code a Python Discord Bot and it saves the channel id and the owner id!我编写了一个 Python Discord Bot,它保存了频道 ID 和所有者 ID!

And if the ticket got closed it need to pop ticket!如果票被关闭,它需要弹出票!

My code looks so:我的代码看起来是这样的:

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

And the json so:而json是这样的:

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

but if i try to close the ticket!但如果我试图关闭票! Its delete the complete tickets.json file!它删除了完整的tickets.json 文件! Like there is nothing in it!好像里面什么都没有!

But i only want to delete the channel id 1 section.但我只想删除channel id 1部分。

And it gives me no error.它没有给我任何错误。

Please help me :c请帮助我:c

First of all, your json script is missing a brace.首先,您的 json 脚本缺少大括号。 It should be:它应该是:

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

Then, your code is designed to do something different from your original intention.然后,您的代码旨在执行与您的初衷不同的事情。 Please, consider the JSON Python module.请考虑JSON Python 模块。 In this way, you will load the json object so that you can manipulate your data as you wish!这样,您将加载 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)

Hope it helps!希望能帮助到你!

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

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