2

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(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).

wjandrea
  • 28,235
  • 9
  • 60
  • 81
cdesar78
  • 93
  • 5
  • 3
    This is honestly an intriguing question that I would love to see answers to, but I'm not sure it's a good fit for StackOverflow, which specifically warns against seeking open-ended, opinion-based advice. Perhaps try the Software Engineering Stack Exchange? – CrazyChucky Dec 01 '21 at 21:31
  • One option might be to look for dataclass to dict/json packages such as [dataclasses-json](https://github.com/lidatong/dataclasses-json) or [dacite](https://github.com/konradhalas/dacite). – jarmod Dec 01 '21 at 21:33
  • 2
    Stackoverflow is to help solve specific technical problems, not open-ended requests for code or advice. – martineau Dec 01 '21 at 21:34
  • 1
    Beside the point, but `id` is a bad variable name since it [shadows](https://en.wikipedia.org/wiki/Variable_shadowing) the [builtin `id`](https://docs.python.org/3/library/functions.html#id). You might want to use something like `id_` instead. For an example, see [my post here](/a/62973285/4518341). – wjandrea Dec 01 '21 at 21:38
  • I hate that stackoverflow deletes these questions. OP and @CrazyChucky use Pydantic BaseModels (or dataclasses) – Tom McLean Dec 01 '21 at 21:38
  • 1
    Thanks guys, I guess this would fit more into Software Eng Stack Exchange - will take it there – cdesar78 Dec 01 '21 at 21:52

0 Answers0