Answer the question
In order to leave comments, you need to log in
How to ignore missing value in json?
Wrote a bot. An unpleasant problem arose: when deleting 1 variable from json, the code stops working correctly, because it cannot find this key. How can you solve this?
#магазин
@bot.command()
async def магазин(ctx):
with open("shop.json","r") as json_file:
a = json.load(json_file)
emb=discord.Embed(title='Магазин',description='.купить [пинг роли/айди роли] - купить роль',color=discord.Colour.blurple())
for i in range(len(a)):
with open("shop.json") as f:
b = json.loads(f.read())
number = int(list(b.keys())[-1])
if a[str(i+1)][2]["guild"] == str(ctx.guild.id):
role=a[str(i+1)][0]["role"]
price=a[str(i+1)][1]["price"]
emb.add_field(name=f'**Товар: **',value=f'**Роль: <@&{role}>, цена: {price}**',inline=False)
await ctx.send(embed=emb)
#удаление из магаза
@bot.command()
async def deleteshop(ctx, role:discord.Role):
with open("shop.json","r") as json_file:
a = json.load(json_file)
with open("shop.json") as f:
b = json.loads(f.read())
with open("db.json","r") as json_file:
c = json.load(json_file)
for i in range(len(a)):
if str(role.id) in a[str(i+1)][0]["role"]:
del a[str(i+1)]
emb = discord.Embed(title='**-Оповещение-**',description='**Роль успешно удалена из магазина.**',color=discord.Colour.green())
await ctx.send(embed=emb)
with open("shop.json","w") as json_file:
json.dump(a, json_file,indent=0)
Answer the question
In order to leave comments, you need to log in
Something like this:
a = {"item1": 1, "item2": 3}
a.get('item1') # существующий ключ
# 1
a.get('item3') # несуществующий ключ. Исключение не будет вызвано - просто выведет None
# None
Or do a check for the existence of the key:
if *переменная*.get("*ключ*") is not None:
# Ключ существует.
else:
# Ключа нету.
# В цикле else делать не нужно.
if "*значение*" in *переменная*:
# Значение существует.
else:
# Тут всё понятно.
# В цикле else писать не нужно.
try:
# Делаем всё что нужно (убираем роль)
except Exception as e:
print(e) # или по другому
# Если ошибка была
if str(role.id) in a[str(i+1)][0]["role"]:
?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question