当我尝试通过我的 python API 请求从 json 中提取时,如何修复/解决此 KeyError?

How can I fix/ workaround this KeyError when I try to extract from a json via my python API request?

我一直在尝试使用来自 api 的一些 covid 数据为 django 数据库播种,并为特定数据类型获取 KeyError - 在源代码中它是 floating_timstamp ("lab_report_date”:“2014-10-13T00:00:00.000”)。 (编辑:不确定类型是否相关,但在这里尽量全面)。

我尝试在 python 中执行更简单的 API 请求,但得到相同的 keyError。下面是我的代码和错误信息。

import requests
response = requests.get("https://data.cityofchicago.org/resource/naz8-j4nc.json")
print(response.json())

输出如下所示:

[
    {
        "cases_age_0_17": "1",
        "cases_age_18_29": "1",
        "cases_age_30_39": "0",
        "cases_age_40_49": "1",
        "cases_age_50_59": "0",
        "cases_age_60_69": "0",
        "cases_age_70_79": "1",
        "cases_age_80_": "0",
        "cases_age_unknown": "0",
        "cases_asian_non_latinx": "1",
        "cases_black_non_latinx": "0",
        "cases_female": "1",
        "cases_latinx": "1",
        "cases_male": "3",
        "cases_other_non_latinx": "0",
        "cases_total": "4",
        "cases_unknown_gender": "0",
        "cases_unknown_race_eth": "1",
        "cases_white_non_latinx": "1",
        "deaths_0_17_yrs": "0",
        "deaths_18_29_yrs": "0",
        "deaths_30_39_yrs": "0",
        "deaths_40_49_yrs": "0",
show more (open the raw output data in a text editor) ...

        "hospitalizations_unknown_gender": "3",
        "hospitalizations_unknown_race_ethnicity": "16",
        "hospitalizations_white_non_latinx": "135"
    }
]

到目前为止一切顺利,但如果我尝试提取问题密钥,我会得到 KeyError:

report_date = []
for i in response.json():
    ls = i['lab_report_date']
report_date.append(ls)

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/var/folders/h3/5wlbmz0s3jb978hyhtvf9f4h0000gn/T/ipykernel_2163/2095152945.py in <module>
      1 report_date = []
      2 for i in response.json():
----> 3     ls = i['lab_report_date']
      4 report_date.append(ls)

KeyError: 'lab_report_date'

使用或不使用 for 循环都会出现此问题。我已经真正转过身来,如果我的代码中有任何错误或遗漏,我深表歉意。

因为数组 response.json() 中有一项不包含键 lab_report_date。当后端数据不那么干净时会发生这种情况。

所以你需要做的就是使用try-except代码块来处理这个异常。下面的代码现在运行良好。

import requests
response = requests.get("https://data.cityofchicago.org/resource/naz8-j4nc.json")
print("The total length of response is %s" % len(response.json()))

report_date = []
for i in response.json():
    try:
        ls = i['lab_report_date']
        report_date.append(ls)
    except:
        print("There is an item in the response containing no key lab_report_date:")
        print(i)

print("The length of report_date is %s" % len(report_date))

以上代码输出结果如下

The total length of response is 592
There is an item in the response containing no key lab_report_date:
{'cases_total': '504', 'deaths_total': '1', 'hospitalizations_total': '654', 'cases_age_0_17': '28', 'cases_age_18_29': '116', 'cases_age_30_39': '105', 'cases_age_40_49': '83', 'cases_age_50_59': '72', 'cases_age_60_69': '61', 'cases_age_70_79': '25', 'cases_age_80_': '14', 'cases_age_unknown': '0', 'cases_female': '264', 'cases_male': '233', 'cases_unknown_gender': '7', 'cases_latinx': '122', 'cases_asian_non_latinx': '15', 'cases_black_non_latinx': '116', 'cases_white_non_latinx': '122', 'cases_other_non_latinx': '30', 'cases_unknown_race_eth': '99', 'deaths_0_17_yrs': '0', 'deaths_18_29_yrs': '0', 'deaths_30_39_yrs': '0', 'deaths_40_49_yrs': '1', 'deaths_50_59_yrs': '0', 'deaths_60_69_yrs': '0', 'deaths_70_79_yrs': '0', 'deaths_80_yrs': '0', 'deaths_unknown_age': '0', 'deaths_female': '0', 'deaths_male': '1', 'deaths_unknown_gender': '0', 'deaths_latinx': '0', 'deaths_asian_non_latinx': '0', 'deaths_black_non_latinx': '0', 'deaths_white_non_latinx': '1', 'deaths_other_non_latinx': '0', 'deaths_unknown_race_eth': '0', 'hospitalizations_age_0_17': '30', 'hospitalizations_age_18_29': '78', 'hospitalizations_age_30_39': '74', 'hospitalizations_age_40_49': '96', 'hospitalizations_age_50_59': '105', 'hospitalizations_age_60_69': '111', 'hospitalizations_age_70_79': '89', 'hospitalizations_age_80_': '71', 'hospitalizations_age_unknown': '0', 'hospitalizations_female': '310', 'hospitalizations_male': '341', 'hospitalizations_unknown_gender': '3', 'hospitalizations_latinx': '216', 'hospitalizations_asian_non_latinx': '48', 'hospitalizations_black_non_latinx': '208', 'hospitalizations_white_non_latinx': '135', 'hospitalizations_other_race_non_latinx': '31', 'hospitalizations_unknown_race_ethnicity': '16'}
The length of report_date is 591

您可以使用 dict get 方法从 json 响应中读取数据,如下所示:-

report_date = []
for i in response.json():
    if type(i) == dict:  # Just check the type to avoid the runtime error.
        ls = i.get('lab_report_date', None)
        if ls:
            report_date.append(ls)

你好,我有一个类似的问题,有时响应是空的 来自 api 导致代码执行停止的请求:

我现在找到了一个简单的解决方案:

假设您有一个 :

requestfromapi = requests.get("https://api-server")

if requestfromapi.json()['data']['something'] != KeyError:

   print(requestfromapi.json()['data']['something'])

// 这将确保您的代码不会停止执行。