检查json对象中的路径是否存在?

时间:2017-08-03 00:28:23

标签: python json dictionary

我目前正在做这样的事情来访问我的json对象中的数组

teacher_topical_array = teacher_obj["medication"]["topical"]

然而,在此之前,我想确保路径teacher_obj["medication"]["topical"]存在,我正在寻找一种更简单的方法来实现这一目标。

现在我知道我可以做这样的事情

if "medication" in teacher_obj:
    if "topical" in teacher_obj["medication"]:
             #yes the key exists

我想知道我是否可以用不同的方式完成上述任务。如果我必须检查像

这样的东西,这可能会更有效
teacher_obj["medication"]["topical"]["anotherkey"]["someOtherKey"]

1 个答案:

答案 0 :(得分:2)

LYBL方法:链get来电,如果您不想使用try-except大括号......

teacher_topical_array = teacher_obj.get("medication", {}).get("topical", None)

EAFP方法:使用try - except块并抓住KeyError

try:
    teacher_topical_array = teacher_obj["medication"]["topical"]
except KeyError:
    teacher_topical_array = []
相关问题