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?
object_hook
will be called for the top-level object, not just the objects in the list.__init__
takes 4 arguments, but you pass 7 infrom_json
(and probably in wrong order). Did you intend to accept all 7 instead of setting three of attributes toNone
? If so, that'd be a perfectdataclass
, and you'll be able to load with[LeagueAcc.from_json(entry) for entry in json.loads(json_object)]
.