0

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

1
  • It’s a list, which suggests it can contain a variable number of items. Apparently it can contain zero or more items. Loop through the list to process all items that are there, which also handles the “zero” case. Alternatively, test whether the list is empty before trying to access it. Commented Mar 18, 2022 at 5:56

1 Answer 1

1

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") 
Sign up to request clarification or add additional context in comments.

2 Comments

FWIW, if data['DATA']: would already suffice.
Thanks @bchooxg your answer fits my needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.