I'm trying to return the 'publisher' and 'title' values of the first entry in this JSON object.
{
"count": 30,
"recipes": [{
"publisher": "Closet Cooking",
"f2f_url": "htt//food2forkcom/view/35171",
"title": "Buffalo Chicken Grilled Cheese Sandwich",
"source_url": "htt//wwwclosetcookingcom/2011/08/buffalo-chicken-grilled-cheese-sandwich.html",
"recipe_id": "35171",
"image_url": "htt//staticfood2forkcom/Buffalo2BChicken2BGrilled2BCheese2BSandwich2B5002B4983f2702fe4.jpg",
"social_rank": 100.0,
"publisher_url": "htt//closetcooking.com"
}, {
"publisher": "All Recipes",
"f2f_url": "htt//food2fork.com/view/29159",
"title": "Slow Cooker Chicken Tortilla Soup",
"source_url": "htt//allrecipescom/Recipe/Slow-Cooker-Chicken-Tortilla-Soup/Detail.aspx",
"recipe_id": "29159",
"image_url": "htt//staticfood2forkcom/19321150c4.jpg",
"social_rank": 100.0,
"publisher_url": "htt//allrecipescom"
}]
}
When I run this code, i can return the object minus the count part at the start.
r = requests.post(url, data = {"key":"aeee9034f8d624f0e6c57fe08e2fd406","q":"chicken"})
recipe=r.json()
print(recipe['recipes'])
However when I try to run:
print(recipe['recipes']['publisher'])
I get the error:
TypeError: list indices must be integers or slices, not str
What should I be doing in my code to print the information:
Closet Cooking, Bacon Wrapped Jalapeno Popper Stuffed Chicken
recipe['recipes'][0]['publisher']recipe['recipes']will now be a list, so you need to treat it as such by accessing the value by its index. The generic way to do this, would be to iterate, in the event you do have multiple values in that list. But, the first comment indicating to use[0]will give you what you are looking for.