Python - 如何检查 JSON 中的键是否为空值?

标签 python json python-3.x

在 JSON 中,我想检查并统计谁拥有学位(最高级别的学位,以及何种类型),谁没有。在计算和检查硕士、博士学位等时,有效,检查是否有 null ,无效。

JSON 的一部分

  "id": 125428,
  "Degree": "Master",

不同的候选人:

  ""id": 125589,
  "Degree": null,

不同的候选人:

  "id": 944987,
  "Degree": "PhD"

我的相关代码如下:

mastercounter = 0
phdcounter = 0
nodeegreecounter = 0

for candidate in response["person"]:
    if item["Degree"]:
        if item["Degree"]["key"] == "Master":
            mastercounter = mastercounter + 1
        if item["license"]["key"] == "PhD":
            phdcounter = phdcounter + 1
   if item["Degree"] == None: 
       nodegreecounter = nodegreecounter + 1

我收到的错误是“TypeError:'NoneType'对象不可下标”

是标识错误,还是代码/我的整个逻辑错误?

最佳答案

使用 if/else 怎么样?

mastercounter = 0
phdcounter = 0
nodeegreecounter = 0

for candidate in response["person"]:
    if item["Degree"]:
        if item["Degree"]["key"] == "Master":
            mastercounter = mastercounter + 1
        if item["license"]["key"] == "PhD":
            phdcounter = phdcounter + 1
    else: 
       nodegreecounter = nodegreecounter + 1

关于Python - 如何检查 JSON 中的键是否为空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59893422/

相关文章:

Python - 测量列表中某个值的最长子序列,并具有误差容忍度

python - 在 PythonAnywhere 上运行 Flask-SocketIO 应用程序会引发 IOError

python - 在 gevent 中检测客户端断开连接

html - 语义网是否使用 XML 而不是 HTML 或 JSON?

python - 给出错误 "the JSON object must be str, not ' 字节'“

javascript - 以更短的方式调用 JSON 对象内部类的成员函数

python - 通过 python selenium 在 Chrome 中限制 CPU

python - 如何使用 Paramiko 从 SFTP 服务器下载最新文件?

python-3.x - 使用 pywinauto 自动化的 Windows 应用程序不会检测 TreeView 内的元素,尽管这些元素有自己的特征

Python3 tkinter 模拟仪表