How can I check if a member ID exists in a JSON?

I am building a bot that should store each member and the corresponding guild in a JSON. This works in the code without problems, but I just can not get one thing right.

Here is the code at first:

    async def on_member_join(self, member):
        with open("src/member.json", "r", encoding='utf-8') as f:
            mlist = json.load(f)

        guild = str(member.id)

        #try:
            #mlist[str(member.guild.id)] = guild
        #except KeyError:
            #print("KEY ERROR")
            #mlist[str(member.guild.id)] = guild

        if guild in mlist:
            return print("IN LIST")
        else:
            mlist[str(member.guild.id)] = guild
            print("NOT IN LIST")

        with open('src/member.json', 'w', encoding='utf-8') as f:
            json.dump(mlist, f, indent=2)

When I enter the server with my account the entry is created, but when I then re-enter the server my print("NOT IN LIST") still comes up.

This is how my JSON looks like:

{
  "731855252277690XXX": "704712637988077XXX" # GuildID : UserID
}

Does anyone here see my error?

I have already tried the following:

  • Reverse search: if guild not in raidlist
  • try and except statements included
  • removed str and converted member.id or guild.id to something else

Answer

What you’re doing right now is storing each guild and user as a single key-value pair. In other words each guild can only store one member. What we can do is to use lists:

async def on_member_join(self, member):
    with open("src/member.json", "r", encoding='utf-8') as f:
        mlist = json.load(f)

    # changed to member id so it's less confusing
    memberid = str(member.id)
    guildid = str(member.guild.id)

    if guildid in mlist:
        if memberid in mlist[guildid]: # the member has already been recorded
            return
        mlist[guildid].append(memberid) # add the member to that guild's list
    else:
        mlist[guildid] = [memberid] # making a list with 1 element

    with open('src/member.json', 'w', encoding='utf-8') as f:
        json.dump(mlist, f, indent=2)

You should clear the JSON before running this code because it’s incompatible with the format you had before.

This way the json will look like:

{
   'GUILDID': ['MEMBERID1', 'MEMBERID2]
}