【发布时间】:2017-07-25 16:10:58
【问题描述】:
我正在尝试返回此 JSON 对象中第一个条目的 'publisher' 和 'title' 值。
{
"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']现在将是一个列表,因此您需要通过其index 访问值来处理它。如果您确实在该列表中有多个值,则执行此操作的通用方法是迭代。但是,指示使用[0]的第一条评论将为您提供所需的内容。 -
啊,我明白了。非常感谢:)
标签: python json python-requests