I'm doing an exercise where I have to find if there some elements in a JSON file and then delete them. For now the problem I have is finding the keys and values.
I have the following JSON called menupizzeria.json
:
{
"tama\u00f1ospizza": ["Personal", "Mediana", "Grande", "Extragrande"],
"borde": [{"Normal": [0, 1, 2, 3]}, {"Queso": [1, 2]}],
"masa": ["delgada", "sazonada"],
"salsas": ["roja", "rosada"],
"Ingredientes": ["cebolla", "3", "f", "g", "h", "r", "s", "", "a", "a"]
}
I'm trying to define a function that searches for the key, for example the key "masa"
and if it is in the JSON then I would like to search for one of the values available in the list, for example "delgada"
, but I'm having a hard time trying to get to the values. This is the code I'm using but I always get the keys. Is there a way to achieve what I want?
def read_menu(path):
with open(path, "r", encoding='utf-8') as file:
menu = json.load(file)
return menu
def get_fields(input_data):
fields = list(input_data)
search = input("Please enter a field to search: ")
result = []
found = fields.index(search)
indice = fields[found]
if indice in fields:
values = input(f"please enter a value to search: ")
for field in input_data:
if input_data[field] == values:
result.append(field)
if len(result) <= 0:
print("NO results where found")
elif len(resultado) == 1:
print(f"one result was found: {result[0]} ")
else:
print(f"found {len(result)} results: ")
else:
print(f"found {len(resultado)} results")
menupi = read_menu("menupizzeria.json")
print(type(menupi))
get_fields(menupi)
CodePudding user response:
Because input_data[field] is a list, it will never be equal to a string entered by the user. To check if a string is IN a list you can use
if value in input_data[field]