T
T
TanderOFF2021-07-29 06:55:58
Python
TanderOFF, 2021-07-29 06:55:58

How to assign value and select it in JSON?

Good afternoon everyone, I'm trying to create an inventory, and command the use of an item from this inventory.

The inventory looks like this:

{
    "Items128": 7,
    "Item29": 3,
    "Item32": 17,
    "Item45": 0,
    "Item93": 4
}

There is a user input (item number)

How to select line number from json by this user number

for row in cursor.execute(f"SELECT invent FROM inv where id={ctx.author.id}"):
                data=json.loads(row[0])
                num =...

Something like this:
client: 2
bot: You have selected an item: Item29

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alan Gibizov, 2021-07-29
@TanderOFF

Something like this, for example:

import json
data = '''{
    "Items128": 7,
    "Item29": 3,
    "Item32": 17,
    "Item45": 0,
    "Item93": 4
}'''
items_dict = json.loads(data)
item_numbers = dict((number, key) for number, key in enumerate(items_dict.keys()))

while True:
    for number, item in item_numbers.items():
        print(f'item {number} - {item}')
    my_number = input('выбери номер:')
    try:
        my_number = int(my_number)
        if my_number in item_numbers.keys():
            print(f'{item_numbers[my_number]}: {items_dict[item_numbers[my_number]]}')
        else:
            print('--- нет такого номера ---')
    except ValueError:
        print(f'--- "{my_number}" - это не номер! ---')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question