Reputation: 25
I'm trying to extract a specific key from JSON data pulled from multiple URLs, which i'm doing successfully, however, after the data prints i am for some reason getting a KeyError, which is confusing because the data is printing..... See code below;
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)
I am trying to pull the AVG float of InDiscards and OutDiscards
The json data is as follows:
{
"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
}
}
},
See the terminal output:
0 0
Traceback (most recent call last):
line 26, in <module>
outDiscards = notification["updates"]["outDiscards"]["value"]["avg"]["float"]
KeyError: 'outDiscards'
as you can see the 0,0 prints correct but with the error
Upvotes: 1
Views: 60
Reputation: 49921
notification["updates"].get("inDiscards", "outDiscards")
yields the value of notification["updates"]["inDiscards"]
if it exists, and "outDiscards"
otherwise, not (as you seem to assume) that both are present.
Upvotes: 1