I am currently making a program for the raspberry pi2 I just brought and with the help from some other members, have got it to work most of the time. however there are some case where it won't work because a field doesnt exist in the json if im correct. the code i have is:
import urllib.request
import json
r = urllib.request.urlopen("http://ift.tt/1NTgHGN").read()
rr = r.decode()
obj = json.loads(rr)
# filter only the b16 objects
b16_objs = filter(lambda a: a['routeName'] == 'B16', obj['arrivals'])
if b16_objs:
# get the first item
b16 = next(b16_objs)
my_estimatedWait = b16['estimatedWait']
my_destination = b16['destination']
print(my_estimatedWait)
My problem is that when routeName B16 is not in the json, an error comes up. I've tried to use the try and catch feature but I could not get this to work. Is there another way of catching this error and displaying a message saying its not present?
The try and catch
try:
b16 = next(b16_objs)
except:
print("there are no records of this")
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire