【发布时间】:2020-05-26 14:58:17
【问题描述】:
我正在尝试从从多个 URL 中提取的 JSON 数据中提取特定的密钥,我正在成功地执行此操作,但是,在数据打印之后,我出于某种原因得到了 KeyError,这令人困惑,因为数据正在打印.....见下面的代码;
for url in URLs:
data = requests.get(url, cookies=cookies, verify=False).json()
notifications = data["notifications"]
for notification in notifications:
if notification["updates"].get("inDiscards", "outDiscards"):
outDiscards = notification["updates"]["outDiscards"]["value"]["avg"]["float"]
inDiscards = notification["updates"]["inDiscards"]["value"]["avg"]["float"]
print(outDiscards, inDiscards)
我正在尝试提取 InDiscards 和 OutDiscards 的 AVG 浮点数
json数据如下:
{
"notifications": [
{
"timestamp": "15002302302",
"path_elements": [
"Devices",
"AAX1238128318",
"versioned-data",
"interfaces",
"data",
"Ethernet2",
"aggregate",
"rates",
"1m"
],
"updates": {
"alignmentErrors": {
"key": "alignmentErrors",
"value": {
"avg": {
"float": 0
},
"max": {
"float": 0
},
"min": {
"float": 0
},
"stddev": {
"float": 0
},
"weight": {
"float": 1
}
}
},
"inDiscards": {
"key": "inDiscards",
"value": {
"avg": {
"float": 0
},
"max": {
"float": 0
},
"min": {
"float": 0
},
"stddev": {
"float": 0
},
"weight": {
"float": 1
}
}
},
"outDiscards": {
"key": "outDiscards",
"value": {
"avg": {
"float": 0
},
"max": {
"float": 0
},
"min": {
"float": 0
},
"stddev": {
"float": 0
},
"weight": {
"float": 1
}
}
},
查看终端输出:
0 0
Traceback (most recent call last):
line 26, in <module>
outDiscards = notification["updates"]["outDiscards"]["value"]["avg"]["float"]
KeyError: 'outDiscards'
你可以看到 0,0 打印正确但有错误
【问题讨论】:
-
正如@scott-hunter Hunter 所说...您在其中一个缺少密钥的通知中收到该错误,您正在迭代那些
notifications,第一个没问题,您会看到打印,但第二个/下一个缺少updates中的outDiscards。下次尝试使用调试器或打印数据并手动检查,KeyError并不是真正的“stackoverflow 问题”。
标签: python json python-3.x python-requests