Python从JSON对象返回键值对

时间:2017-07-25 16:10:59

标签: python json python-requests

我正在尝试返回此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

2 个答案:

答案 0 :(得分:0)

recipe['recipes']是一个对象列表,因此您可以迭代它:

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

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

如果要扩展结果并在返回的列表中包含更多字段或更多元素,这会给您一些灵活性。

答案 1 :(得分:-1)

'recipes'键包含多个食谱的列表

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

将返回列表中第一个食谱的发布者。