Search code examples
pythonjsonpython-requeststextbox

python issues with KeyError: skip over errors when data is not in the json?


One is having trouble with a basic Python script that calls an API and then displays the info on a simple textbox. The issue is that sometimes, the Application Programming Interface (API) will have all the information, and sometimes it will not. When it has all the information, the script completes perfectly and displays all the information as laid out; however, sometimes the API does not have a specific section in it, which then causes a KeyError.

It is either required to completely skip over the area if that section is not in the API or preferably have a text that sits there and says "no info" and if the API has that section, it should be out.

Below is the script:


  data = {'name': 'Kev', 'connected': 'ONLINE', 'time': '2024-03-03T23:01:00Z', 'up-loader': [{'uploaded': 'Yes', 'upload-time': '2024-03-03T18:01:00Z'}]}

    # Main Info - allways in the json
  InfoNAME = data["name"]
  InfoCONN = data["connected"]
  InfoTIME = data["time"]
    # This info is only in the json sometimes - here is where the problem is
  InfoUPLOAD = data['up-loader'][0]["uploaded"]
  InfoUPTIME = data['up-loader'][0]["upload-time"] 

# Take info from above and load it onto the chart below
    # deletes all the text that is currently in the TextBox 
  text_box.delete('1.0', END)   
    # insert new data into the TextBox
# Name
  text_box.insert(END, "Name:  ")
  text_box.insert(END, InfoNAME)
# Online status  
  text_box.insert(END, "Status: ")
  text_box.insert(END, InfoCONN)
# Last online Time  
  text_box.insert(END, "Last Online: ")
  text_box.insert(END, InfoTIME)
# Upload logger
  text_box.insert(END, "Was there an upload:")  
  text_box.insert(END, InfoUPLOAD)
# Upload time
  text_box.insert(END, "When was the upload: ")
  text_box.insert(END, InfoUPTIME)

I look forward to hearing from you.


Solution

  • You have two options.

    You can specifically check if the key is present by using the in keyword:

    if somekey in mydata:
        # yes it is present, so it is safe to
        # access mydata['somekey']
    

    Or you can use the .get() function, which allows you to supply a default value to use if the key is not found:

    value = mydata.get(somekey, 'Oops this was not found')