2017-08-03 127 views
0

我目前做这样的事情。然而这样做,我想确保路径teacher_obj["medication"]["topical"]存在前访问数组中的json对象检查json对象中的路径是否存在?

teacher_topical_array = 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"] 
+0

您可以使用异常处理try:teacher_obj [“medication”] [“topical”] [“anotherkey”] [“someOtherKey”],除了KeyError:...'。 – DyZ

+0

@SnakesandCoffee哇。相关联的dupe与我的答案类似。 –

回答

1

的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 = [] 
+0

我喜欢LYBL的方法将与那 –

+0

@JamesFranco当然。随意标记接受,如果它的工作。 –