我目前正在做类似的事情来访问我的 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"]
最佳答案
LYBL 方法:链式 get
调用,如果您不想使用 try- except
大括号...
teacher_topical_array = teacher_obj.get("medication", {}).get("topical", None)
<小时/>
EAFP方法:使用 try
- except
block 并捕获 KeyError
。
try:
teacher_topical_array = teacher_obj["medication"]["topical"]
except KeyError:
teacher_topical_array = []
关于python - 检查json对象中的路径是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45472960/