Python 从 JSON 对象返回键值对



我正在尝试返回此 JSON 对象中第一个条目的"发布者"和"标题"值。

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

是一个对象列表,因此您可以迭代它:

要返回此 JSON 对象中第一个条目的"发布者"和"标题"值,您可以使用列表推导并获取结果集合的第一个元素:

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

如果要扩展结果并在返回的列表中包含更多字段或更多元素,这为您提供了一定的灵活性。

'recipes'键包含多个配方的列表

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

将返回列表中第一个配方的发布者。

最新更新