2017-07-25 14 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 ['recipes']'が* list *になることを理解しています。その* index *で値にアクセスすることで、そのように扱うことができます。これを行う一般的な方法は、そのリストに複数の値がある場合、反復することです。しかし、 '[0] 'を使うことを示す最初のコメントは、あなたが探しているものを与えるでしょう。 – idjaw

+0

また、https://stackoverflow.com/questions/16129652/accessing-json-elements – idjaw

答えて

-1

'recipes'キーに複数のレシピのリストが含まれています

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

は、リスト内の最初のレシピの発行元を返します。

+3

多分この光沢のある金のハンマーを使ってこの質問を欺くことができます。 :) – idjaw

0

recipe['recipes']は、このようにあなたがそれを反復することができ、オブジェクトのリストである:

リストの内包表記を使用して、最初に取得することができ、このJSONオブジェクトの最初のエントリの「発行者」と「タイトル」の値を返すには結果として、コレクションの要素:あなたが結果を展開したいとより多くのフィールド、または返されたリストに複数の要素が含まれている場合

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

これは、あなたの柔軟性のビットを提供します。

関連する問題