Python:Json Data into Class Instance varaibles

时间:2016-09-21 18:42:05

标签: python python-2.7

我正在尝试创建一个名为Movie的类。我已经声明了实例变量。我正在调用OMDB API,我想存储为其分配变量。但这似乎并没有起作用。即使我打印json_Data,它也不会打印任何东西。任何人都可以指出我正确的方向。我知道我可以将数据存储到字典中。但是如何将它存储在一个类中。我是一个仍在学习python的新手。

class Movie(object):
    """ Class provides a structure to store Movie information """



    def __init__(self, imdb_id, title = None, release_year = None, rating = None, run_time = None, genre = None, director = None, actors = None, plot = None, awards = None, poster_image = None, imdb_votes = None, youtube_trailer = None):
        self.imdb_id = imdb_id
        self.title = title
        self.release_year = release_year
        self.rating = rating
        self.run_time = run_time
        self.genre = genre
        self.director = director
        self.actors = actors
        self.plot = plot
        self.awards = awards
        self.poster_image = poster_image
        self.imdb_votes = imdb_votes
        self.youtube_trailer = youtube_trailer


    def get_api_data(self):
        """
            Method retrieves and parses information for each movie based on imdb_id
        """
            #URL for OMDBI
        url = "http://www.omdbapi.com/?i="+self.imdb_id+"&plot=full&r=json&v=1"
        try:
            response = urllib.urlopen(url)

        except URLERROR as e:
            if hasattr(e, 'reason'):
                print ("Unable to reach a server.")
                print 'Reason: ', e.reason
            elif hasattr(e, 'code'):
                print "Server is unable to fulfill the request."
                print 'Error Code: ', e.code
            else:
                json_data = json.loads(response.read())
                self.imdb_id = json_data["imdbID"].encode("utf8","ignore")
                self.title = json_data["Title"].encode("utf8","ignore")
                self.release_year = int(json_data["Released"].split("")[-1])
                self.rating = json_data["imdbRating"].encode("utf8", "ignore")
                self.run_time = json_data["Runtime"].encode("utf8", "ignore")
                self.genre = json_data["Rated"].encode("utf8", "ignore")
                self.director = json_data["Director"].encode("utf8", "ignore")
                self.actors = json_data["Actors"].encode("utf8", "ignore")
                self.plot = json_data["Plot"].encode("utf8", "ignore")
                self.awards = json_data["Awards"].encode("utf8", "ignore")
                self.poster_image = json_data["Poster"].encode("utf8", "ignore")
                self.imdb_votes = json_data["imdbVotes"].encode("utf8", "ignore")

是否建议将返回的数据存储为字典而不是为每种电影类型创建一个类?

1 个答案:

答案 0 :(得分:1)

此类提供存储电影信息的结构:

class Movie(object):

def __init__(self, imdb_id, title = None, release_year = None, rating = None, run_time = None, genre = None, director = None, actors = None, plot = None, awards = None, poster_image = None, imdb_votes = None, youtube_trailer = None):
    self.imdb_id = imdb_id
    self.title = title
    self.release_year = release_year
    self.rating = rating
    self.run_time = run_time
    self.genre = genre
    self.director = director
    self.actors = actors
    self.plot = plot
    self.awards = awards
    self.poster_image = poster_image
    self.imdb_votes = imdb_votes
    self.youtube_trailer = youtube_trailer


def get_api_data(self):
    """
        Method retrieves and parses information for each movie based on imdb_id
    """
        #URL for OMDBI
    url = "http://www.omdbapi.com/?i="+self.imdb_id+"&plot=full&r=json&v=1"
    try:
        response = urllib.urlopen(url)

    except URLERROR as e:
        if hasattr(e, 'reason'):
            print ("Unable to reach a server.")
            print 'Reason: ', e.reason
        elif hasattr(e, 'code'):
            print "Server is unable to fulfill the request."
            print 'Error Code: ', e.code

    # if urllib.urlopen() succeeds, the code jumps to here
    json_data = json.loads(response.read())
    self.imdb_id = json_data["imdbID"].encode("utf8","ignore")
    self.title = json_data["Title"].encode("utf8","ignore")
    self.release_year = int(json_data["Released"].split("")[-1])
    self.rating = json_data["imdbRating"].encode("utf8", "ignore")
    self.run_time = json_data["Runtime"].encode("utf8", "ignore")
    self.genre = json_data["Rated"].encode("utf8", "ignore")
    self.director = json_data["Director"].encode("utf8", "ignore")
    self.actors = json_data["Actors"].encode("utf8", "ignore")
    self.plot = json_data["Plot"].encode("utf8", "ignore")
    self.awards = json_data["Awards"].encode("utf8", "ignore")
    self.poster_image = json_data["Poster"].encode("utf8", "ignore")
    self.imdb_votes = json_data["imdbVotes"].encode("utf8", "ignore")