Я пытаюсь извлечь определенный c ключ из JSON данных, извлеченных из нескольких URL-адресов, что я делаю успешно, однако после печати данных я по какой-то причине получаю 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)
Я пытаюсь вытащить AVG float из InDiscards и OutDiscards
Данные 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 печатает правильно, но с ошибкой