首页 > 解决方案 > 如何在 Python 中编辑编码的 json 文件

问题描述

我目前正在使用 Python 开发 Discord 机器人。为了保存数据,我创建了一个 .tmp 文件,用于存储 json 格式的数据文本。

我必须对其进行编码才能立即写入文件(我还在文件中进行了一些值检查)。

因为它是编码的,所以我无法使用以下代码编辑 json:

emojiU = '\N{THUMBS UP SIGN}'
emojiD = '\N{THUMBS DOWN SIGN}'
cnd_Member = [member for member in ctx.guild.members if str(data['roles_id']['AmongUs']) in str(member.roles) and (str(member.status) == "online" or str(member.status) == "idle") and member.id != ctx.author.id]
tmpfile = open("my_file.tmp", "wb+", 0) #List that store connected user with a specific role

for i, member in enumerate(cnd_Member): # for connected member with the specific role

    DM = discord.utils.get(client.get_all_members(), id=member.id)
    Sstring = "***" + Sender + "***" + '   veux jouer à  ***' + game + '***.\n :thumbsup:  si vous êtes chaud ou  :thumbsdown:  si vous ne l\'êtes pas'
    msg = await DM.send(embed=createEbd(des=Sstring, img=imgLink)) #send DM to the member

    if i == 0:
       save = '{{"{}":{{"msgId":{}, "reaction":"None"}}, '.format(member.id, msg.id)

    elif i == len(list(cnd_Member))-1:
         save = '"{}":{{"msgId":{}, "reaction":"None"}}}}'.format(member.id, msg.id)

    else :
         save = '"{}":{{"msgId":{}, "reaction":"None"}}, '.format(member.id, msg.id)

    await msg.add_reaction(emojiU ) #Bot add reaction to the DM message
    await msg.add_reaction(emojiD) #Bot add reaction to the DM message
    tmpfile.write(save.encode("utf-8")) #creating the json file with data


    @client.event
    async def on_reaction_add(reaction, user):
          
          if user.id != client.user.id :
             if reaction.emoji == emojiU:
                tmpfile.seek(0)
                rd = tmpfile.read() # Getting the content of file 
                binf = json.loads(rd.decode('utf-8'))


                binf["{}".format(user.id)]["msgId"] = thxObj.id   #Updating the json with new value
                binf["{}".format(user.id)]["reaction"] = "True"   #Updating the json with new value

                json.dump(binf, tmpfile) #writing to file fail because it's not encoded

          
             if reaction.emoji == emojiD:
                tmpfile.seek(0)
                rd = tmpfile.read() # Getting the content of file 
                binf = json.loads(rd.decode('utf-8'))


                binf["{}".format(user.id)]["msgId"] = thxObj.id   #Updating the json with new value
                binf["{}".format(user.id)]["reaction"] = "False"   #Updating the json with new value

                json.dump(binf, tmpfile) #writing to file fail because it's not encoded

使用 json.dumps 然后对其进行编码并使用 tmpfile.write 将其写入文件中,但它只附加数据,而不是编辑 tmpfile 中的现有 json。

感谢帮助

标签: pythonjsonencodingdiscord.py

解决方案


我找到了如何处理它。

我将所有数据存储在 JSON 格式文件中,当用户添加反应时,它会编辑文件。当我需要发布表时,它会读取 JSON 文件。

编码或未编码,我只需要编辑json.loads和重写文件就可以了


推荐阅读