user2142407
user2142407

Reputation:

How would I search for values in a dictionary?

I am making an opensource twitch.tv API wrapper for python, so far I have:

import urllib2
import json
import time
waittime = 1
baseurl = 'https://api.twitch.tv/kraken/'

class twitchchannelinfo():
    def __init__ (self,channel):
        self.channel = channel
        time.sleep(waittime)
        self.dict1 = json.loads(urllib2.urlopen(baseurl + 'channels/' + channel).read())

    def getstatus(self):
        return self.dict1 ['status']
    def getdisplay_name(self):
        return self.dict1 ['display_name']
    def getmature(self):
        return self.dict1 ['mature']
    def getchanurl(self):
        return self.dict1 ['url']
    def getcreated_at(self):
        return self.dict1 ['created_at']
    def getteams(self):
        return self.dict1 ['teams']
    def getgame(self):
        return self.dict1 ['game']
    def getupdated_at(self):
        return self.dict1 ['updated_at']

and I would like to add error checking to this API. The server will return a json response like this for an error:

{
    "error": "Unprocessable Entity",
    "status": 422,
    "message": "Channel 'deeman' is not available on Twitch"
}

which I then convert to a dictionary using json.loads. How would I check this dictionary for the value "error" or is there a better way of doing this?

Upvotes: 0

Views: 96

Answers (3)

Sudipta Chatterjee
Sudipta Chatterjee

Reputation: 4670

if 'error' in self.dict1:
  # do blah

Upvotes: 0

javex
javex

Reputation: 7544

I would recommend to do:

if 'error' in self.dict1:
    raise ValueError("%s: %s" % (self.dict1["error"], self.dict1["message"]))

Upvotes: 2

GodMan
GodMan

Reputation: 2641

try:
    self.dict1[u'error']
except KeyError:
    ## Do something here

This is just another approach using try...except

Upvotes: 0

Related Questions