我试图检查JSON
数据中是否存在某些属性,这些数据存储为字典:
import json
testJsonString = """
{
"a": {
"b": {
"c": {
"x": "Value One",
"y": "Value Two"
}
}
}
}
"""
testDict = json.loads(testJsonString)
if 'a' in testDict:
if 'b' in testDict['a']:
if 'c' in testDict['a']['b']:
if 'x' in testDict['a']['b']['c']:
print(testDict['a']['b']['c']['x'])
if 'y' in testDict['a']['b']['c']:
print(testDict['a']['b']['c']['y'])
这将根据需要打印:
Value One
Value Two
但是,如果顶级嵌套属性之一是null
(由json.loads()
转换为None
):
testJsonString = """
{
"a": {
"b": null
}
}
"""
我得到以下错误:
if 'c' in testDict['a']['b']:
TypeError: argument of type 'NoneType' is not iterable
有办法解决这个问题吗?我被难住了
在Python中使用嵌套dict是一件痛苦的事情,我建议使用:https://github.com/cdgriffith/Box
您可以使用用户定义的函数检查空安全性
另一种处理错误的方法是使用try/except,这是一种快速但肮脏的方法
我通过为每个
if
级别添加一个None
检查来修复它。不确定这是否是最好的方法,但它是有效的:相关问题 更多 >
编程相关推荐