Python returning key value pair from JSON object -


this question has answer here:

i'm trying return 'publisher' , 'title' values of first entry in 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 run code, can return object minus count part @ start.

r = requests.post(url, data = {"key":"aeee9034f8d624f0e6c57fe08e2fd406","q":"chicken"}) recipe=r.json() print(recipe['recipes']) 

however when try run:

print(recipe['recipes']['publisher']) 

i error:

typeerror: list indices must integers or slices, not str 

what should doing in code print information:

closet cooking, bacon wrapped jalapeno popper stuffed chicken 

recipe['recipes'] list of objects, can iterate on it:

to return 'publisher' , 'title' values of first entry in json object can use list comprehension , first element of resulting collection:

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

this gives bit of flexibility if want expand result , include more fields, or more elements in returned list.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -