Home > Back-end >  Python json output KeyError: 'Link Annotations - dynamic json
Python json output KeyError: 'Link Annotations - dynamic json

Time:04-19

I have a json output where the output is dynamic, sometimes there is the object below, but sometimes is empty so no dict is available in the output and create an error when the output missing this object: KeyError: 'Link Annotations'".

In my python code I'm using this access and it's fine but just when the object is available - > 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
      ]
    },

CodePudding user response:

It depends what you want to do if Link Annotations is missing.

To avoid errors you can use get method:

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

or try, except block:

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

But how to handle if key is missing is up to you.

  • Related