Python returning key value pair from JSON object -
this question has answer here:
- python accessing nested json data 4 answers
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
Post a Comment