我目前做这样的事情。然而这样做,我想确保路径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"]
您可以使用异常处理try:teacher_obj [“medication”] [“topical”] [“anotherkey”] [“someOtherKey”],除了KeyError:...'。 – DyZ
@SnakesandCoffee哇。相关联的dupe与我的答案类似。 –