【问题标题】:Problems storing information of JSON into dictionary for loop in python在 python 中将 JSON 信息存储到字典 for 循环中的问题
【发布时间】:2020-10-03 09:08:10
【问题描述】:

我是 API 和 Web 开发方面的新手。所以如果我的问题非常基本,我很抱歉:(。

我想创建一个基于所含成分的食物食谱网络浏览器。我使用 2 个查询 url 来获取信息,因为我需要访问 2 个 json 文件。第一个根据用户搜索的成分获取每个食谱的id,第二个根据第一个url中返回的id获取每个食谱的信息。

我的代码是这个:

#Function that return id's of recipes that contains the word queried by user.
def ids(query):
    try:
        api_key  = os.environ.get("API_KEY")
        response = requests.get(f"https://api.spoonacular.com/recipes/autocomplete?apiKey={api_key}&query={urllib.parse.quote_plus(query)}")
        response.raise_for_status()
    except requests.RequestException:
        return response
    try: 
        ids = []
        quotes = response.json()
        for quote in quotes:
            ids.append(quote['id'])
        return ids
    except (KeyError,TypeError, ValueError):
        return None

#save inside a list named "ids", the id's of recipes that contains the ingredient chicken
ids = ids("chicken")

#function that return the differents options of recipes based in the ids.
def lookup(ids):
    for ID in ids:
        try:
            api_key  = os.environ.get("API_KEY")
            response = requests.get(f"https://api.spoonacular.com/recipes/{ID}/information?apiKey{api_key}&includeNutrition=false")
            response.raise_for_status()
        except requests.RequestException:
            return response

我遇到的主要问题是我不知道如何存储响应中返回的信息,您可能会注意到我在“查找”函数中使用了一个循环来获取列表 ID 中包含的所有 ID 的响应,但考虑到我将为每个 ID 获得 1 个响应(例如,如果我有 6 个 id,我将在 json 文件中获得 6 个不同的响应,其中包含 6 个不同的信息)。

最后我要存储的信息就是这个

quote = response.json()
results = {'id':quote["id"],'title':quote["title"],'url':quote["sourceUrl"]}

这是带有数据样本的链接和用于获取 json 的 url

https://spoonacular.com/food-api/docs#Get-Recipe-Information

我一直在尝试使用 python 将位于不同 json 文件中的信息存储在字典中。

任何形式的帮助都会很棒!

【问题讨论】:

  • 我建议 lookup() 应该返回一个字典。 id 将是字典的键。字典的值将是响应的 json。我建议在您的问题中提供示例数据。返回响应的特定 API 并不那么重要。示例数据和一个工作示例(不需要 API 密钥等私有信息)使编写答案变得更加容易。
  • @AaronBentley 我更新了信息人 :) 数据样本在这个 url spoonacular.com/food-api/docs#Get-Recipe-Information

标签: python json loops web


【解决方案1】:

您最好使用dict,其结构与您返回的食谱相匹配:

假设 API 返回namedurationdifficulty,这些是您稍后将使用的字段,并且您还可以为您的程序保存除食谱之外的其他数据,您可以使用dict。如果不是这种情况,只需使用代表单个配方的 listdicts

#just a dummy setup to simulate getting different recipes back from the API
one_response = {"name" : "Chicken and Egg", "duration" : 14, "difficulty" : "easy"} 
another_response = {"name" : "Chicken square", "duration" : 100, "difficulty" : "hard"} 

def get_recipe(id): 
    if id == 1: 
        return one_response
    else:
        return another_response 

ids = [1,2]
# Here would be other information maybe as well, that you capture somewhere else. If you don't have this then simply use a list with recipes dicts inside..
queried_recipes = {"recipes" :[] }

for i in ids: 
    # Here you simply add a recipes to your recipes dict
    queried _recipes["recipes"].append(get_recipe(i)) 

print (queried_recipes)
OUT: {'recipes': [{'name': 'Chicken and Egg', 'duration': 14, 'difficulty': 'easy'}, {'name': 'Chicken square', 'duration': 100, 'difficulty': 'hard'}]}

print(queried_recipes["recipes"][0]["duration"])
OUT: 14

【讨论】:

    【解决方案2】:

    您可能想改用https://spoonacular.com/food-api/docs#Get-Recipe-Information-Bulk。这将在一个 JSON 文档中为您提供所需的所有信息,而无需循环重复调用 https://api.spoonacular.com/recipes/{ID}/information

    但是,要回答原来的问题:

    def lookup(ids):
        api_key  = os.environ.get("API_KEY")
        results = []
        for ID in ids:            
            response = requests.get(f"https://api.spoonacular.com/recipes/{ID}/information?apiKey{api_key}&includeNutrition=false")
            response.raise_for_status()
            quote = response.json()
            result = {'id':quote["id"],'title':quote["title"],'url':quote["sourceUrl"]}
            results.append(result)
        return results
    

    【讨论】:

      猜你喜欢
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 2019-12-31
      • 2020-06-25
      • 1970-01-01
      • 2019-07-16
      • 2013-06-15
      • 1970-01-01
      相关资源
      最近更新 更多