0

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
J-Alex
  • 6,881
  • 10
  • 46
  • 64
A. Blair
  • 11
  • 1
  • 4
  • 2
    The inner dict is embedded in a list: `recipe['recipes'][0]['publisher']` – Moses Koledoye Jul 25 '17 at 16:11
  • Realize that `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. – idjaw Jul 25 '17 at 16:12
  • Also: https://stackoverflow.com/questions/16129652/accessing-json-elements – idjaw Jul 25 '17 at 16:15
  • Ahhh, I see. Thank you very much :) – A. Blair Jul 25 '17 at 16:16

2 Answers2

0

recipe['recipes'] is a list of objects, thus you can iterate over it:

To return the 'publisher' and 'title' values of the first entry in this JSON object you can use list comprehension and get the first element of the resulting collection:

recipes = [{element['publisher']: element['title']} for element in recipe['recipes']][0]

This gives you a bit of flexibility if you want to expand the result and include more fields, or more elements in the returned list.

Stanley Kirdey
  • 602
  • 5
  • 20
-1

The 'recipes' key contains a list of multiple recipes

recipe['recipes'][0]['publisher']

will return the publisher of the first recipe in the list.

nosklo
  • 217,122
  • 57
  • 293
  • 297