Huismori
Huismori

Reputation: 33

Python Json Handling Empty or Null

I am trying to handle json data from a link, my problem is when there are all the fields everything works fine but when there is and empty field or card id does not exist I get error, this is the code I am using ;

def getData(url):
     response = urllib.request.urlopen(url)
     if(response.getcode()==200):
         data = response.read()
         jsonData = json.loads(data)
     else:
         print("Error occured", response.getcode())
     return jsonData


def bring(card_id):
     url = "http://link" + card_id
     data = getData(url)
     name = data['DATA'][0]['NAME']
     counter = data['DATA'][0]['COUNTER']
     dt = data['DATA'][0]['DATE']
     photo = data['DATA'][0]['PHOTO_LINK']
     if photo is not None:
        img_load = WebImage(photo).get()
        Photo_frame.configure(image=img_load)
        Photo_frame.image=img_load

     if name is not None:
        Name_frame.config(text=name)

     if int(counter) <= 0:
        Counter_frame.config(text=counter, bg='red')
     else:
        Counter_frame.config(text=counter, bg='green')

     if dt is not None:
        Date_frame.config(text=dt, bg="yellow")
     time.sleep(5)
     clear()

Button(root, text="Counter Left", width=20, command=lambda: bring("445445445"))

and this is the error I am getting ;

Exception in Tkinter callback Traceback (most recent call last):   File "/usr/lib/python3.9/tkinter/__init__.py", line 1892, in __call__
    return self.func(*args)   File "/root/info.py", line 178, in <lambda>
    KIGS = Button(root, text="Counter Left", width=20, command=lambda: bring("445445445"))   File "/root/info.py", line 117, in bring
    name = data['DATA'][0]['NAME'] IndexError: list index out of range

data from the json link comes like shown below;

if card_id exist in the system I get following return from json page ;

{"SUCCESS":1,"ERROR":null,"DATA":[{"NAME":"My Name Is","COUNTER":"1234567890","DATE":"01.01.2022","PHOTO_LINK":"http://link/photo_1.jpg"}]}

if card_id does not exist then I get following return from json page ;

{"SUCCESS":1,"ERROR":null,"DATA":[]}

Thanks in advance

Upvotes: 0

Views: 3724

Answers (1)

bchooxg
bchooxg

Reputation: 35

So the issue is arising from an index out of range exception ( which means that you are trying to access an index that is not present in a list )

So to handle this for your case since there would be an empty list returned even if there is no data, you can check the size of the list if it has a value before you run your code logic

So what you would do is add an if statement above the bring function

if len(data['DATA']) > 0 : 
  # Add logic
else:
  # Handle empty value

So it would look something like that

def bring(card_id):
     url = "http://link" + card_id
     data = getData(url)
     if len(data['DATA']) > 0 : 
       name = data['DATA'][0]['NAME']
       counter = data['DATA'][0]['COUNTER']
       dt = data['DATA'][0]['DATE']
       photo = data['DATA'][0]['PHOTO_LINK']
       if photo is not None:
          img_load = WebImage(photo).get()
          Photo_frame.configure(image=img_load)
          Photo_frame.image=img_load

       if name is not None:
          Name_frame.config(text=name)

       if int(counter) <= 0:
          Counter_frame.config(text=counter, bg='red')
       else:
          Counter_frame.config(text=counter, bg='green')

       if dt is not None:
          Date_frame.config(text=dt, bg="yellow")
       time.sleep(5)
       clear()
    else:
      print("no data received") 

Upvotes: 1

Related Questions