无法从JSON数据中的列表和嵌套列表中提取某些值

2024-05-16 03:21:16 发布

您现在位置:Python中文网/ 问答频道 /正文

从URL上的JSON数据:https://api.punkapi.com/v2/beers我正在尝试输入其“方法”要求mash_temp >=65摄氏度和持续时间为mash >=75的饮料名称

例如:

{'mash_temp': [{'temp': {'value': 65, 'unit': 'celsius'}, 'duration': 75}],
 'fermentation': {'temp': {'value': 10, 'unit': 'celsius'}}, 'twist': None}

我的代码如下:

import json
import requests

url = 'https://api.punkapi.com/v2/beers'
content = requests.get(url).content
j = json.loads(content)
print(j)
for each in filter(lambda data: data["mash_temp"] >= "65", j):
    print(each["name"],each["mash_temp"])

它打印整个列表和可用的嵌套列表,但我无法获得饮料的名称,需要mash_temp >=65摄氏度,持续时间为mash >=75

此外,对于“hop”类型的“配料”,需要查找所有id、饮料名称、酒花名称、酒花数量(含单位)和酒花属性


Tags: https名称comapicontenttempv2持续时间
1条回答
网友
1楼 · 发布于 2024-05-16 03:21:16

嘿,老兄,在能够检索信息、编写一步一步访问这些内部列表的代码、提高可读性并在调试过程中使您的生活更轻松之前,您必须进一步研究数据集以了解其结构。(简单过复杂)

# retrieve information from url
url = 'https://api.punkapi.com/v2/beers'
content = requests.get(url).content
j = json.loads(content)

# Going into the dataset a step at a time
for data in j:
    # retrieve the method
    method = data['method']
    
    # retrieve the mash_temp information from the method
    # note the mash_temp is saved in a list
    mash_temp = method['mesh_temp][0]
    
    # not all temp or duration contain values, some of them
    # are None values, this is a catch all try statement
    # you can write a more defined try/except statement
    try:
        if mash_temp['temp']['value'] >= 65 and mash_temp['duration'] >= 75:
            print(data['name'], ' -', mash_temp)
    except:
        # define what to do here if anything temp or duration
        # contains None values
        pass

相关问题 更多 >