Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to handle missing JSON nested keys from an API response in python?

Here is the JSON response I get from an API request:

{  
    "associates": [
        {
            "name":"DOE",
            "fname":"John",
            "direct_shares":50,
            "direct_shares_details":{
               "shares_PP":25,
               "shares_NP":25
            },
            "indirect_shares":50,
            "indirect_shares_details": {
                  "first_type": {
                      "shares_PP": 25,
                      "shares_NP": 0
                  },
                  "second_type": {
                      "shares_PP": 25,
                      "shares_NP": 0
                  }
            }
        } 
    ]
}

However, in some occasions, some values will be equal to None. In that case, I handle it in my function for all the values that I know will be integers. But it doesn’t work in this scenario for the nested keys inside indirect_shares_details:

{  
    "associates": [
        {
            "name":"DOE",
            "fname":"John",
            "direct_shares":50,
            "direct_shares_details":{
               "shares_PP":25,
               "shares_NP":25
            },
            "indirect_shares":None,
            "indirect_shares_details": None
            }
        } 
    ]
}

So when I run my function to get the API values and put them in a custom dict, I get an error because the keys are simply inexistant in the response.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def get_shares_data(response):
    associate_from_api = []
        for i in response["associates"]:
            associate_data = {
            "PM_shares":  round(company["Shares"], 2),
            "full_name": i["name"] + " " + ["fname"]
            "details": {
                    "shares_in_PM":    i["direct_shares"],
                    "shares_PP_in_PM": i["direct_shares_details"]["shares_PP"],
                    "shares_NP_in_PM": i["direct_shares_details"]["shares_NP"],
                    "shares_directe":  i["indirect_shares"],
                    "shares_indir_PP_1": i["indirect_shares_details"]["first_type"]["shares_PP"],
                    "shares_indir_NP_1": i["indirect_shares_details"]["first_type"]["shares_NP"],
                    "shares_indir_PP_2": i["indirect_shares_details"]["second_type"]["shares_PP"],
                    "shares_indir_NP_2": i["indirect_shares_details"]["second_type"]["shares_NP"],
                }
            }
            for key,value in associate_data["details"].items():
                if value != None:
                    associate_data["details"][key] = value * associate_data["PM_shares"] / 100
                else:
                    associate_data["calculs"][key] = 0.0
            associate_from_api.append(associate_data)
    return associate_from_api

I’ve tried conditioning the access of the nested keys only if the parent key wasn’t equal to None but I ended up declaring 3 different dictionaries inside if/else conditions and it turned into a mess, is there an efficient way to achieve this?

>Solution :

You can try accessing the values using dict.get('key') instead of accessing them directly, as in dict['key'].

Using the first approach, you will get None instead of KeyError if the key is not there.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading