检查JSON属性是否存在

2024-06-02 05:21:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图检查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

有办法解决这个问题吗?我被难住了


Tags: 数据injsonif字典属性valueone
3条回答

在Python中使用嵌套dict是一件痛苦的事情,我建议使用:https://github.com/cdgriffith/Box

from box import Box

def unwrap(b: Box) -> Optional[Box]:
    return None if b == Box() else b

box = Box(testDict)
value = unwrap(box.a.b.c.x)
if value is not None:
    print(value)

您可以使用用户定义的函数检查空安全性

import json

def Check(key, col):
    return key in col if col is not None else False

testJsonString = """
{
    "a": {
        "b": null
    }
}
"""

testDict = json.loads(testJsonString)

if Check('a', testDict):
    if Check('b', testDict['a']):
        if Check('c', testDict['a']['b']):
            if Check('x', testDict['a']['b']['c']):
                print(testDict['a']['b']['c']['x'])
            if Check('y', testDict['a']['b']['c']):
                print(testDict['a']['b']['c']['y'])

另一种处理错误的方法是使用try/except,这是一种快速但肮脏的方法

import json

testJsonString = """
{
    "a": {
        "b": {
            "c": {
                "x": "Value One",
                "y": "Value Two"
            }
        }
    }
}
"""

testDict = json.loads(testJsonString)

try:
    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'])
except:
    print('Something went wrong in the dictionary')

我通过为每个if级别添加一个None检查来修复它。不确定这是否是最好的方法,但它是有效的:

testJsonString = """
{
    "a": {
        "b": {
            "c": {
                "x": "Value One",
                "y": "Value Two"
            }
        }
    }
}
"""

testDict = json.loads(testJsonString)

if testDict and 'a' in testDict:
    if testDict['a'] and 'b' in testDict['a']:
        if testDict['a']['b'] and 'c' in testDict['a']['b']:
            if testDict['a']['b']['c'] and 'x' in testDict['a']['b']['c']:
                print(testDict['a']['b']['c']['x'])
            if testDict['a']['b']['c'] and 'y' in testDict['a']['b']['c']:
                print(testDict['a']['b']['c']['y'])

相关问题 更多 >