M
M
Mind20772022-02-18 21:33:32
Python
Mind2077, 2022-02-18 21:33:32

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)

the code in which the error occurs
#удаление из магаза
@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)

deletion code from db
spoiler
{
"1": [
{
"role": "943923969856241674"
},
{
"price": "123"
},
{
"guild": "864466654091804682"
}
],
"2": [
{
"role": "944248827370700880"
},
{
"price": "10000"
},
{
"guild": "864466654091804682"
}
],
"3": [
{
"role": "944215477956268082"
},
{
"price": "13000"
},
{
"guild": "864466654091804682"
}
],
"4": [
{
"role": "938738379212865547"
},
{
"price": "100000"
},
{
"guild": "938718264874373170"
}
]
}

The database itself

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladimir Kuts, 2022-02-18
@fox_12

Something like this:

a = {"item1": 1, "item2": 3}

a.get('item1')  # существующий ключ
# 1
a.get('item3')  # несуществующий ключ. Исключение не будет вызвано - просто выведет None
# None

M
Matvey Kot, 2022-02-19
@MatweyCAT

Or do a check for the existence of the key:

if *переменная*.get("*ключ*") is not None:
    # Ключ существует.
else:
    # Ключа нету.
    # В цикле else делать не нужно.

Or on the existence of a value (as in the question):
if "*значение*" in *переменная*:
    # Значение существует.
else:
    # Тут всё понятно.
    # В цикле else писать не нужно.

Or the simplest option:
try:
    # Делаем всё что нужно (убираем роль)
except Exception as e:
    print(e)  # или по другому
    # Если ошибка была

In general, I did not understand a little where the error was. Here: if str(role.id) in a[str(i+1)][0]["role"]:?

M
Mind2077, 2022-02-19
@Mind2077

By the way, I tried to do with 1 option. It has become slightly better: now the code works adequately up to the deleted part of the db, and then it just scores on the rest of the db. Still better than a complete breakdown of the team, but not suitable

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question