将一些JSON密钥转换为Python对象

时间:2019-06-27 19:32:34

标签: python json

我有一个如下所示的Python类:

class Game:
    """Holds all game related attributes - usually one instance created per game."""

    def __init__(
        self,
        game_id,
        game_type,
        date_time,
        game_state,
        venue,
        home,
        away,
        preferred,
        live_feed,
        season,
    ):

        self.game_id = game_id
        self.game_type = game_type
        self.date_time = date_time
        self.game_state = game_state
        self.venue = venue
        self._live_feed = live_feed
        self.home_team = home
        self.away_team = away
        self.season = season

当前,我通过从API响应中解析JSON并挑选一些值并将其传递到此类的init()函数中来创建此类的实例。

将API响应传递到init()函数中并从该类中的JSON字典中解析/挑选这些属性是否更好(因此,围绕该类的所有逻辑都放在一个地方)是否更好?设置类级别的属性?

例如,我在main()函数中获取了这些值,然后将它们传递给类。

# Create a Game Object
    gameobj_game_id = game_info["gamePk"]
    gameobj_game_season = game_info["season"]
    gameobj_game_type = game_info["gameType"]
    gameobj_date_time = game_info["gameDate"]
    gameobj_game_state = game_info["status"]["abstractGameState"]

game_obj = Game(gameobj_game_id, gameobj_game_type, gameobj_date_time, gameobj_game_state...)

但是该代码是从对象创建逻辑中抽象出来的。

任何建议将不胜感激!

1 个答案:

答案 0 :(得分:1)

您可能想要定义一个类方法,其作用是从此类响应中补充“正确”字段。

class Game:
    """Holds all game related attributes - usually one instance created per game."""

    def __init__(
        self,
        game_id,
        game_type,
        date_time,
        game_state,
        venue,
        home,
        away,
        preferred,
        live_feed,
        season,
    ):

        self.game_id = game_id
        self.game_type = game_type
        self.date_time = date_time
        self.game_state = game_state
        self.venue = venue
        self._live_feed = live_feed
        self.home_team = home
        self.away_team = away
        self.season = season

    @classmethod
    def from_json(cls, resp):
        return Game(
            game_id=resp["gamePk"],
            game_type=resp["gameType"],
            ...
        )

类型本身就是“方法”(因为Game(...)间接等同于Game.__new__(...))提供了创建对象的规范方法,并且无法确定每条信息的来源。其他类方法可以充当同一数据的各种来源的包装器。