3

So I am pulling data (list of JSON) from an API and want to parse it into Python objects. However the JSON objects of my list returned from my API need to be transformed a bit to fit into my object. I don't know if this transformation should happen inside of the __init__ function or outside of the object.

Data pulled from API:

{
    "data": [
        {
            "league": {
                "id": 62,
                "name": "Ligue 2",
                "type": "League"
            },
            "country": {
                "name": "France",
                "code": "FR"
            }
        }
    ]
}

Option 1 (transformation happens inside the object):

class League:
    def __init__(self, data):
        self.id = data["league"]["id"]
        self.name = data["league"]["name"]
        self.country_code = data["country"]["code"]

for d in data["data"]:
    league = League(data=d)

Option 2:

class League:
    def __init__(self, id, name, country_code):
        self.id = id
        self.name = name
        self.country_code = country_code

for d in data["data"]:
    league = League(
        id=d["league"]["id"],
        name=d["league"]["name"],
        country_code=d["country"]["code"])

The transformation will be more complex, but you get the idea hopefully. Looking for advice to figure out which of the 2 options makes the most sense (leaning towards option 2).

1 Answer 1

12

Consider that you might want to create League objects from other sources. Then you'd need to construct a dictionary in the specific shape from your JSON source in order to do so. So, option 2 would be preferred.

If your class has to be tightly coupled to the dictionary representation read from JSON at all, consider using a classmethod as an alternative constructor:

class League:
    def __init__(self, id, name, country_code):
        self.id = id
        self.name = name
        self.country_code = country_code
    @classmethod
    def from_json(cls, data):
        league = data['league']
        country = data['country']
        return cls(id=league['id'], name=league['name'], country_code=country['code'])

for d in data["data"]:
    league = League.from_json(d)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.