pythonjsonclassobjectdeserialization

Deserializing JSON list into class objects not able to extract attributes


I'm struggling to deserialize my json-file into an array of objects of my class LeagueAcc.

I wanna fill a list with objects of class LeagueAcc called:

accounts = []

I have loaded my JSON successfully with this:

with open('dataprint.json', 'r') as openfile:
    json_object = json.load(openfile)

Current Solution(not working)

I've added the return LeagueAcc function into my class and tried to call it .

def from_json(json_dct):
      return LeagueAcc(
          json_dct['elo'],
          json_dct['id'],
          json_dct['loginname'],
          json_dct['puuid'],
          json_dct['pw'],
          json_dct['summoner'],
          json_dct['tagline'])```

This is the call from the main code:

json_deserialized = json.loads(json_object, object_hook=LeagueAcc.LeagueAcc.from_json)
class LeagueAcc:
     def __init__(self, loginname,pw, summoner, tagline):
          self.loginname = loginname
          self.summoner = summoner
          self.pw = pw
          self.tagline = tagline
          self.elo = None
          self.id = None
          self.puuid = None

Json File

{
  "LeagueAcc": [
    {
      "elo": "MASTER 98 LP",
      "id": "321",
      "loginname": "pet",
      "puuid": "321",
      "pw": "peter",
      "summoner": "ottie",
      "tagline": "888"
    },
    {
      "elo": "MASTER 98 LP",
      "id": "123",
      "loginname": "petereerr",
      "puuid": "123",
      "pw": "peterererreer",
      "summoner": "ottie",
      "tagline": "888"
    }
  ]
}

How can I get a list accounts[] filled with two (2) objects of class LeagueAcc successfully initialized and filled with the data from the JSON?


Solution

  • To reduce amount of boilerplate code I'd suggest to use something like pydantic / dataclasses / etc:

    from pydantic import BaseModel
    
    body = {
        "LeagueAcc": [
            {
                "elo": "MASTER 98 LP",
                "id": "321",
                "loginname": "pet",
                "puuid": "321",
                "pw": "peter",
                "summoner": "ottie",
                "tagline": "888"
            },
            {
                "elo": "MASTER 98 LP",
                "id": "123",
                "loginname": "petereerr",
                "puuid": "123",
                "pw": "peterererreer",
                "summoner": "ottie",
                "tagline": "888"
            }
        ]
    }
    
    
    class LeagueAcc(BaseModel):
        elo: str
        id: str
        loginname: str
        puuid: str
        pw: str
        summoner: str
        tagline: str
    
    
    league_accs = [LeagueAcc.model_validate(item) for item in body["LeagueAcc"]]
    

    Or even more:

    class LeagueAccs(BaseModel):
        league_acc: list[LeagueAcc] = Field(alias="LeagueAcc")
    
    
    league_accs = LeagueAccs.model_validate(body)