如何使Json的类成员可序列化

2024-10-02 10:21:35 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码

with open('setting1.json',mode='r',encoding='utf8')as jfile:
    jdata = json.load(jfile)

@bot.command(pass_context=True)
async def data(ctx):
    a1=[]
    author=ctx.message.author
    a1.append(author)

    jdata["a1"]=a1

    with open('setting1.json',mode='w',encoding='utf8')as jfile:
        json.dump(jdata,jfile)

我想用json保存成员数据,并运行以下代码:

TypeError: Object of type 'Member' is not JSON serializable

我怎样才能修复它(或者根本不可能)?谢谢


Tags: json密码modea1aswithloadopen
1条回答
网友
1楼 · 发布于 2024-10-02 10:21:35

错误显示“TypeError:type'Member'的对象不可JSON序列化”。看起来discord.py返回的是'Member'类型,而不是字符串类型。要解决这个问题,只需将变量'author'转换为字符串,方法是将表示author = ctx.message.author的行转换为author = str(ctx.message.author)。这就是修复该错误所需的全部操作。但我想我会这么做的

@bot.command(pass_context=True)
async def data(ctx):
    author = str(ctx.message.author)

    with open('setting1.json', 'r', encoding='utf8') as jfile:
        if (jfile): loaded = json.load(jfile) # If they's something in this file (Should be a list in this case) then load the data as variable 'loaded'
        else: loaded = [] # But if it's empty then assign a list to the 'loaded' variable

        if (author not in loaded): # Thought you may need this. Checks if the user's name is already there, If it's not then it'll add it, but if it is then it won't add it
            loaded.append(author) # Append to the data we loaded or the list we created
            with open('setting1.json', 'w', encoding='utf8') as jfile: # Open the file again this time in write mode
                json.dump(loaded, jfile, ensure_ascii=False, indent=4, sort_keys=True) # Dump to the file and done.

相关问题 更多 >

    热门问题