Python 有没有办法避免json中的重复值?
它运行得很好,但每次我重新运行它时,它都会添加已经在json文件中的用户id,从而导致重复的值。有办法解决吗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
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)
可能会有所帮助。真是太棒了,它成功了@乌普斯