I am working on my first coding project (interactive cookbook) and I have met a road block, I am trying to print the name of the array (chocolate chip cookies) by entering the ingredients name (flour) in the terminal, I am using python to do this. here’s an example of my json file code:
{
"Recipes": [
"chocolate chip cookie",[
{
"ingredients": "flour"
},
{
"instructions": "Step 1: Preheat Oven to 375"
},
{
"category": "Cookies"
}
]
]
}
here’s an excerpt of my python code:
response = input("are you looking for recipes with ingredients on hand (if so please enter 'ingredients') or are you looking for something to cook/bake? (if so please enter 'Cook/Bake')n")
if response == "ingredients":
print("please enter ingredients")
ingredients = input("enter ingredients separated by commas: ")
ingredients = ingredients.split(",")
for x in ingredients:
import json
#pulling ingredients from cookbook.json(?)
with open('cookbook.json', 'r') as f:
data = json.load(f)
3
Answers
It would be better to structure your data like this
Best to move the things you only need to do once, to the top of the code
This includes the import and the reading of the JSON.
While you are testing the program, the question-and-answer pattern will drive you mad
You would be better off with this sort of layout while you are developing. Later you can uncomment the questions.
Your data structure is quite unwieldy for the purpose at hand.
Based on the data you do have, the process of finding a recipe name (overly complex as it may) could go as follows:
First I would recomand chanign the structure of the json file to, for example:
Now you have a list called Recipes each item in this list will be a single recipe.
Each recipe has 4 varialbes: name, ingredients, instructions, category.
This way you can loop over every ingredient in every recipe to see if they match.
If you only want to see the first result put a break in the is statement.
I also noticed that you put the import inside of the for loop, please don’t do this and put it at the top of the file to ensure that it only gets imported once.
Also don’t put the with open() statments in the for loop. It’s best to use it once to read the data and save that data in a variable:
To answer your initial question: