2017-07-25 75 views
0

我試圖返回此JSON對象中第一個條目的'publisher'和'title'值。從JSON對象返回鍵值對的Python

{ 
    "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" 
    }] 
} 

當我運行這段代碼時,我可以在開始時返回對象減去計數部分。

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

然而,當我嘗試運行:

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

我得到的錯誤:

TypeError: list indices must be integers or slices, not str 

我應該在我的代碼做打印的信息:

Closet Cooking, Bacon Wrapped Jalapeno Popper Stuffed Chicken 
+2

內部字典嵌入在列表中:'recipe ['recipes'] [0] ['publisher']' –

+0

瞭解'recipe ['recipe']'現在將成爲* list *,所以您需要通過其*索引*訪問值來對待它。執行此操作的通用方法是迭代,如果* do *在該列表中有多個值。但是,第一個表示使用'[0]'的註釋會給你你正在尋找的東西。 – idjaw

+0

另外:https://stackoverflow.com/questions/16129652/accessing-json-elements – idjaw

回答

-1

The 'recipes'密鑰包含多個配方列表

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

將返回列表中第一個配方的發佈者。

+3

也許你可以使用閃亮的金錘子來欺騙這個問題。 :) – idjaw

0

recipe['recipes']爲對象的列表,從而你可以遍歷它:

要返回「出版商」和「稱號」的第一項的值,你可以使用列表理解這個JSON對象,並獲得第一結果集合的元素:

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

,如果你想擴展的結果,包括更多的領域,或返回列表中的多個元素這給你一點靈活性。