【问题标题】:Python - Json data prints but also gives KeyErrorPython - Json 数据打印但也给出 KeyError
【发布时间】: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


【解决方案1】:

notification["updates"].get("inDiscards", "outDiscards") 产生 notification["updates"]["inDiscards"] 的值(如果存在),否则产生 "outDiscards" 的值,而不是(如您所假设的)两者都存在。

【讨论】:

  • 在哪个版本的python中,您可以以这种方式检查dict中是否存在某些键? ... AFAIK notification["updates"].get("inDiscards", "outDiscards") 将为您提供密钥 "inDiscards" 的值(如果存在)或字符串 "outDiscards" 作为“默认值”如果密钥 "inDiscards" 不存在于字典中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-01
  • 2018-10-05
  • 1970-01-01
  • 2020-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多