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