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

标签 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"]

最佳答案

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/

相关文章:

c# - Json.Net 可以嵌入到可执行文件中吗?

json - 如何使用 Enum 类型的字段执行 Typesafe JSON?

c# - linq过滤后的Dictionary结构如何保存

python - 在字典中解包元组

python - "char_to_ix = { ch:i for i,ch in enumerate(sorted(chars)) }"是做什么的?

python - 在 Scrapy 中使用项目

python正则表达式提取用户名:password or email:password in mixed delimited csv

javascript - 无法访问 React Component 中的 Javascript 对象

python : How can I test that my error has been logged on sentry?

python - Flask 在向自身发送 post 请求时挂起