Reputation: 17
Code:
@bot.command()
async def start(ctx):
edit = []
file = open("wallet.json", "r+")
for line in file:
temp = json.loads(line)
edit.append(temp)
userid = []
for i in range(len(edit)):
userid.append(edit[i]["id"])
user = str(ctx.author.id)
if userid.count(user) > 0:
await ctx.reply("You already have an account")
else:
embed = nextcord.Embed(title = "Blablabla", description = "Blablabla")
embed.set_footer(text = "Blablabla")
await ctx.send(embed = embed)
entry = {"id": user, "gold": 0, "fyre": 0, "faction": None}
json.dump(entry, file)
Json: empty
Error:
userid.append(edit[i]["id"])
TypeError: list indices must be integers or slices, not str
Essentially, I'm trying to make a json file that adds an object every time this Discord command is ran. You can ignore everything with the words "Nextcord", "Embed", and "ctx" in them. When I run the command, the json gets an object inside an array. This causes my for loop that's adding stuff to the userid list to get a Typeerror, as it was designed to load a big jumble of objects, not arrays.
Inside wallet.json:
[{"id": "My Discord ID, in my real code it's there", "gold": 0, "fyre": 0, "faction": null}]
Another part of my code which does a similar thing worked flawlessly, so there must be something wrong with this piece of code. Please help.
Upvotes: 1
Views: 42
Reputation: 66
The issue here is that you are loading the json wrong; and thus your userid
list is empty.
The below snippet populates your userid
variable properly:
@bot.command()
async def start(ctx):
file = open("wallet.json", "r+")
edit = json.load(file)
userid = [i["id"] for i in edit]
user = str(ctx.author.id)
if userid.count(user) > 0:
await ctx.reply("You already have an account")
else:
embed = nextcord.Embed(title = "Blablabla", description = "Blablabla")
embed.set_footer(text = "Blablabla")
await ctx.send(embed = embed)
entry = {"id": user, "gold": 0, "fyre": 0, "faction": None}
json.dump(entry, file)
Upvotes: 1