Python API请求-For循环导致索引错误

时间:2020-10-23 19:03:31

标签: python

Python的新手。...在我的代码中遇到了for循环的困扰,特别是Key:'topic_title'的分配。

我一直收到“列表索引超出范围”错误。嵌套在“ solicitation_topics”上的JSON响应,因此我认为我需要传递索引,并且在尝试直接从python终端直接访问时可以使用该索引,但是在该函数内,我不断收到错误消息。任何帮助将不胜感激。

import requests, json

def get_solicitations():
    # api-endpoint
    URL = "https://www.sbir.gov/api/solicitations.json"

    # defining a params dict for the parameters to be sent to the API 
    PARAMS = {"keyword": 'sbir'} 

    # sending get requfiest and saving the response as response object 
    r = requests.get(url = URL, params = PARAMS) 

    # extracting data in json format 
    api_data = r.json() 

    # storing selected json data into a dict
    solicitations = []

    for data in api_data:
        temp = {
            'solicitation_title': data['solicitation_title'],
            'program': data['program'],
            'agency': data['agency'],
            'branch': data['branch'],
            'close_date': data['close_date'],
            'solicitation_link': data['sbir_solicitation_link'],
            'topic_title': data['solicitation_topics'][0]['topic_title'],
        }

        solicitations.append(temp) 
    return (solicitations)

JSON响应的片段如下所示:

[
    {
        "solicitation_title": "Interactive Digital Media STEM Resources for Pre-        College and Informal Science Education Audiences (SBIR) (R43/R44 Clinical Trial Not Allowed) ",
        "solicitation_number": "PAR-20-244 ",
        "program": "SBIR",
        "phase": "BOTH",
        "agency": "Department of Health and Human Services",
        "branch": "National Institutes of Health",
        "solicitation_year": "2020",
        "release_date": "2020-06-25",
        "open_date": "2020-08-04",
        "close_date": "2022-09-03",
        "application_due_date": [
            "2020-09-04",
            "2021-09-03",
            "2022-09-02"
        ],
        "occurrence_number": null,
        "sbir_solicitation_link": "https://www.sbir.gov/node/1703169",
        "solicitation_agency_url": "https://grants.nih.gov/grants/guide/pa-files/PAR-20-244.html",
        "current_status": "open",
        "solicitation_topics": [
            {
                "topic_title": "Interactive Digital Media STEM Resources for Pre-College and Informal Science Education Audiences (SBIR) (R43/R44 Clinical Trial Not Allowed) ",
                "branch": "National Institutes of Health",
                "topic_number": "PAR-20-244 ",
                "topic_description": "The educational objective of this FOA is to provide opportunities for eligible SBCs to submit NIH SBIR grant applications to develop IDM STEM products that address student career choice and health and medicine topics for: (1) pre-kindergarten to grade 12 (P-12) students and teachers or (2) informal science education (ISE) audiences. The second educational objective is to inform the American public that their quality of health is defined by lifestyle. If this message is understood, people can begin to live longer and reduce the healthcare burden to society. Therefore, this FOA also encourages IDM STEM products that will increase public health literacy and stimulate behavioral changes towards a healthier lifestyle. The research objective of this FOA is the development of new educational products that will advance our understanding of how IDM STEM-based gaming can improve student learning. It is anticipated that increasing underserved and minority student achievement in STEM fields through IDM STEM resources will encourage these students to pursue health-related careers that will increase their economic and social opportunities. A diverse health care workforce will help to expand health care access for the underserved, foster research in neglected areas of societal need, and enrich the pool of managers and policymakers to meet the needs of a diverse population.\r\n\r\nIDM is a bridge technology that converts game-based activities from a social pastime to a powerful educational tool that challenges students with problem solving, conceptual reasoning and goal-oriented decision making. Well-designed IDM products mimic successful teacher pedagogy and exploit student interest in games for learning. IDM STEM products also integrate imbedded learning, e.g., what the student knows and new knowledge gained in the gaming process, into problem solving skills. IDM products provide real time student assessment. Unlike standardized classroom testing where student achievement is a pass or fail process, IDM-based assessment is interactive, does not punish the student, and provides feedback on how to move to the next level of play. IDM products are intended to generate long-term changes in student performance, educational outcomes and career choices.\r\n\r\nThis FOA also encourages IDM STEM products that will increase public health literacy and stimulate behavioral changes towards a healthier lifestyle. Types of applications submitted to this FOA may vary with the target audience, scientific content, educational purpose and method of delivery. IDM STEM products may include but are not limited to: game-based curricula, resources that promote attitude changes toward learning, new skills development, teamwork and group activities, public participation in scientific research (citizen science) projects, and behavioral changes in lifestyle and health. IDM STEM products designed to increase the number of underserved students, e.g., American Indian, Alaska Native, Pacific Islanders, African American, Hispanic, disabled, or otherwise underrepresented individuals considering careers in basic, behavioral or clinical research are encouraged.\r\n\r\nIDM STEM products may be designed for use in-classroom or out-of-classroom settings, e.g., as supplements to existing classroom curricula, for after-school science clubs, libraries, hospital waiting rooms and science museums. IDM products may target children in group settings or individually, with or without adult or teacher participation or supervision.\r\n\r\nThe proposed project may use any IDM gaming technology or platform but the platform chosen should be accessible to the target group.\r\n\r\n",
                "sbir_topic_link": "https://www.sbir.gov/node/1703171",
                "subtopics": []
            }
        ]
    },
]

1 个答案:

答案 0 :(得分:1)

复制代码,看来solicitation_topics可以是一个空列表。我将此行添加到您的函数中:

print(f"title = {data['solicitation_title']}, topics: {data['solicitation_topics']}")

我发现这个(几个)空容器:

title = NIH,CDC和FDA为小企业创新研究资助申请而进行的PHS 2020综合招标(不允许父母SBIR [R43 / R44]临床试验),主题:[]

您将需要弄清楚该如何防范。 如果您想跳过空的内容,可以在循环的顶部放置一个continue

if not data['solicitation_topics']:
    continue

或者,如果您仍然希望保留没有主题的邀请,则应在上方生成所需的标题,然后在您的临时文件中使用该标题:

if data['solicitation_topics']:
    topic_title = data['solicitation_topics'][0]['topic_title']
else:
    topic_title = 'Not Supplied'