将Json列表反序列化为类对象无法提取属性

问题描述 投票:0回答:1

我正在努力将我的 json 文件反序列化为我的 LeagueAcc 类的对象数组

我想用名为 LeagueAcc 的类的对象填充一个列表

accounts = []

我已经成功加载了我的json:

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

json_object = json.load(openfile)

当前解决方案(不起作用)

我已将 return LeagueAcc 函数添加到我的类中并尝试调用它

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'])```

这是主代码的调用

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 文件

{
  "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"
    }
  ]
}

我怎样才能获得一个列表accounts[],其中填充了LeagueAcc类的2个对象,成功初始化并填充了json中的数据?

python json class object deserialization
1个回答
0
投票

为了减少样板代码的数量,我建议使用类似

pydantic
/
dataclasses
/ 等的东西:

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"]]
© www.soinside.com 2019 - 2024. All rights reserved.