我試圖返回此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 ['recipe']'現在將成爲* list *,所以您需要通過其*索引*訪問值來對待它。執行此操作的通用方法是迭代,如果* do *在該列表中有多個值。但是,第一個表示使用'[0]'的註釋會給你你正在尋找的東西。 – idjaw
另外:https://stackoverflow.com/questions/16129652/accessing-json-elements – idjaw