【问题标题】:Python returning key value pair from JSON object [duplicate]Python从JSON对象返回键值对[重复]
【发布时间】: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


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 也许你可以用那把闪亮的金锤来欺骗这个问题。 :)
    猜你喜欢
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 2020-03-06
    • 2013-06-24
    • 2017-07-12
    • 2019-12-12
    • 2015-02-18
    • 2020-05-20
    相关资源
    最近更新 更多