R
R
RusKFA2021-11-25 15:42:02
Python
RusKFA, 2021-11-25 15:42:02

How to remove value from Json?

I have an array keys
619f830581964572595838.png

that holds stuff

I use del mas[i]
but it doesn't work

Here is my code:

with open('keys.json', 'r', encoding='utf-8') as f: #открыли файл с данными
            mas = json.load(f) #загнали все, что получило

    print(key)
    for i in range(len(mas)):
        if (mas[i] == key):
            print(mas)

            await bot.send_message(
                    chat_id=message.chat.id,
                    text =  "okay" 
                    ) 
            text = 1
            sql.execute(f'UPDATE users SET sub = {text}  WHERE user_id = {message.from_user.id}')
            int(i)
            del mas[i]
      
        else:
            await bot.send_message(
                    chat_id=message.chat.id,
                    
                    text = "не окей" )

key is the data that the user entered.
That is, what is the essence of the script? If what the user entered matches the value from json, then some values ​​\u200b\u200bare added to the user status, everything works except for removing the element from json

And here is the error (IndexError: list index out of range)
619f8400806eb852220469.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2021-11-25
@RusKFA

You should not iterate the list that you change in the same loop. Well, SQL queries would be compiled differently

if key in mas:
    await bot.send_message(chat_id=message.chat.id, text =  "okay")
    sql.execute('UPDATE users SET sub = ?  WHERE user_id = ?', (text, message.from_user.id))
    mas.remove(key)
else:
    await bot.send_message(chat_id=message.chat.id, text = "не окей" )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question