Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 有没有办法避免json中的重复值?_Python_Json_Discord.py - Fatal编程技术网

Python 有没有办法避免json中的重复值?

Python 有没有办法避免json中的重复值?,python,json,discord.py,Python,Json,Discord.py,它运行得很好,但每次我重新运行它时,它都会添加已经在json文件中的用户id,从而导致重复的值。有办法解决吗 with open('./data/faction1.json','r', encoding='utf-8') as f: try: faction = json.load(f) except ValueError: faction = {} faction['users'] = [] class clan(commands.Cog): def

它运行得很好,但每次我重新运行它时,它都会添加已经在json文件中的用户id,从而导致重复的值。有办法解决吗

with open('./data/faction1.json','r', encoding='utf-8') as f:
  try:
    faction = json.load(f)
  except ValueError:
    faction = {}
    faction['users'] = []


class clan(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def join(self, ctx):

        new_user = ctx.author.id
        if new_user not in faction['users']:
            faction['users'][new_user] = ctx.author.name
            await ctx.send("you have been added to the faction")
            with open('./data/faction1.json', 'w') as f:
                json.dump(faction, f)
            
        else:
            await ctx.send("already in faction")

json将键保存为字符串,但
ctx.author.id
是一个整数。使用
new\u user=str(ctx.author.id)
可能会有所帮助。真是太棒了,它成功了@乌普斯