Python-如何检查 JSON 中的键是否具有空值?
2020-01-24
5773
在 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' 对象不可下标”
是标识错误,还是代码/我的整个逻辑?
3个回答
那么使用 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
tkrishtop
2020-01-24
这取决于您的 JSON 是如何组织的。我怀疑响应是一系列人员。像这样:
response = [{"id": "1", "Degree": "Master"}, {"id": "2", "Degree": null}]
因此您应该使用:
for person in response:
您只需要一个人的一个属性(名为“Degree”)。
因此,如果一个人是一系列属性,则代码变为:
for person in response:
if person["Degree"] is None:
nodegreecounter = nodegreecounter + 1
elif person["Degree"] == "Master":
mastercounter = mastercounter + 1
elif person["Degree"] == "PhD":
phdcounter = phdcounter + 1
如果您的 JSON 组织方式不同,您应该在寻求建议之前解释 JSON 结构。
如果您的 JSON 看起来像这样:
{"key11": {"id": "1", "Degree": "Master"}, "key12": {"id": "2", "Degree": null}}
代码可以是:
for key in response:
if response[key]["Degree"] is None:
nodegreecounter = nodegreecounter + 1
elif response[key]["Degree"] == "Master":
mastercounter = mastercounter + 1
elif response[key]["Degree"] == "PhD":
phdcounter = phdcounter + 1
或
for key, person in response.items():
if person["Degree"] is None:
nodegreecounter = nodegreecounter + 1
elif person["Degree"] == "Master":
mastercounter = mastercounter + 1
elif person["Degree"] == "PhD":
phdcounter = phdcounter + 1
Sergey
2020-01-24
正确访问字典键。
mastercounter = 0
phdcounter = 0
nodeegreecounter = 0
for candidate in response["person"]:
if item["Degree"]:
if item["Degree"] == "Master":
mastercounter = mastercounter + 1
if item["Degree"] == "PhD":
phdcounter = phdcounter + 1
else:
nodegreecounter = nodegreecounter + 1
Shweta Chandel
2020-01-24