Python json output KeyError: 'Link Annotations - dynamic json

Python json output KeyError: 'Link Annotations - dynamic json

我有一个 json 输出,其中输出是动态的,有时下面有对象,但有时是空的,因此输出中没有可用的字典,当输出缺少此对象时会产生错误:键错误:'Link Annotations'”。

在我的 python 代码中,我正在使用此访问权限,它很好,但只是在对象可用时 - > Link = process["Link Annotations"]

"full": {
"Link Annotations": {
  "E.460.15763456.34": [
    {
      "Link": "http://link",
      "Dimensions": [
        28.5,
        2773,
        307.5,
        2789.5
      ]
    },
    {
      "Link": "http://link",
      "Dimensions": [
        28.5,
        2756.5,
        255.75,
        2773
      ]
    },

如果缺少 Link Annotations,这取决于您想做什么。

为避免错误,您可以使用 get 方法:

Link = process.get("Link Annotations", None)
if not Link:
    print("Key: 'Link Annotations' is missing.")
    # your code here

tryexcept块:

try:
    Link = process["Link Annotations"]
except KeyError:
    print("Key: 'Link Annotations' is missing.")
    # your code here

但是如果key丢失了怎么处理就看你的了