Preventing script-exiting exceptions when finding JSON values that might not exist?

Viewed 18

How would I prevent KeyError when grabbing a value from an API querey JSON?

Explanation: I am calling an API for a user one at a time. Each user returns a JSON with a set of information. I am creating a dictionary from a few specific pieces of information in that JSON. However, sometimes users don't have a specific value (such as Role or Username). How can I write my program so it doesn't throw an exception and end the program when it can't find this value? And instead of throwing an exception it just enters a blank for that specific dictionary value? I have looked into .get but I cannot seem to get it to work with my specific use case.

Code:

APResponse = requests.request('POST', APurl, headers=headers, json={'offset': str(AssetPandaCurrentUser), 'limit': '1'})
    APResponseJSON = APResponse.json()

    AssetPandaUserDict = {
        "Username": [APResponseJSON['objects'][0]['data']['field_52']],
        "Role": [APResponseJSON['objects'][0]['data']['field_49']['value']],
        "User Status": [APResponseJSON['objects'][0]['data']['field_6']['value']],
        "Laptop Status": [],
        "Laptop Serial": []
    }

So if "Role" is blank or missing in the JSON, it will just set "Role" to a blank instead of throwing a KeyError exception.

I have tried this:

 "Username": [APResponseJSON.get(['objects'][0]['data']['field_52'])]

But I receive error "TypeError: string indices must be intergers.

Any ideas?

1 Answers

You can use get() method.

For example:


"Role": [APResponseJSON.get(['objects'][0].get("data", {}).get("field_49"{}).get("value")]

of course if you are sure that APResponseJSON.get(['objects'][0] exists.

You can also prepare pydantic model to easily parse your response.

Related