Home > Software engineering >  Pulling Values from a JSON Dataset that Match a Keyword
Pulling Values from a JSON Dataset that Match a Keyword

Time:06-08

Currently working on a school project based on a JSON dataset about a weapon list in a videogame. I've been trying to add functionality where the user can click a button that runs code filtering the dataset down to the forms containing the key-word. Below is the back end code for one of the functions, returning all forms where name = dagger

def wpn_dagger():
    with open('DSweapons.json', encoding='utf-8') as outfile:
        data = json.load(outfile)
        wpn_list = []
    for dict in data:
        if dict in ['name'] == 'dagger':
            wpn_list.append(data)
        print(wpn_list)
        return wpn_list

Whilst I do not get any errors when I run the code the only output to the terminal is an empty set of [] brackets. Any help on this issue would be much appreciated.

CodePudding user response:

if dict in ['name'] == 'dagger' is wrong syntax for what you want

when written like that ['name'] is a list containing the string 'name', so dict in ['name'] is checking if dict is in that list (will be always false) and then we check if the result of that == 'dagger', i.e. the whole thing reads as if False == 'dagger'

Try this:

def wpn_dagger():
    with open('DSweapons.json', encoding='utf-8') as outfile:
        data = json.load(outfile)
    wpn_list = []
    for weapon in data:
        if weapon['name'] == 'dagger':
            wpn_list.append(weapon)
    print(wpn_list)
    return wpn_list

CodePudding user response:

Indentation in python is very important. Your for loop needs to be indented so it operates inside the with context manager.

Secondly, dict is a keyword in python, so use something different if you need to name a variable.

Finally you can get an object out of your form using .get('name') on the dictionary, it's at least easier to read in my opinion.

In summary, something like this (not tested):

def wpn_dagger():
    with open('DSweapons.json', encoding='utf-8') as outfile:
        data = json.load(outfile)
        wpn_list = []
        for form in data:
            if form.get('name') == 'dagger':
                wpn_list.append(form)
            print(wpn_list)
    return wpn_list
  • Related