如何将对象列表的JSON文件还原为原Python Player对象结构
问题:如何将JSON文件还原为包含Player类对象的字典结构?
我尝试读取由以下Python字典生成的JSON文件,该字典包含Player类的对象列表:
players = { 'Players': [ Player('P1', 3, 2, 0, 0, 3, 0.3, "sup"), Player('P2', 3, 2, 3, 4, 2, 0.5, "adc"), Player('P3', 4, 4, 5, 3, 3, 0.7, "mid"), ] }
Player类的定义如下:
class Player: def __init__(self, id:str="", top:int = 0, jg:int = 0, mid:int = 0, adc:int = 0, sup:int = 0, win_rate:int = 0, preferred_line:str = "top"): self.id = id self.position = {"top": top, "jg": jg, "mid": mid, "adc": adc, "sup": sup} self.win_rate = win_rate self.preferred_line = preferred_line
生成的JSON文件内容如下:
{"Players": [{"id": "P1", "position": {"top": 3, "jg": 2, "mid": 0, "adc": 0, "sup": 3}, "win_rate": 0.3, "preferred_line": "sup"}, {"id": "P2", "position": {"top": 3, "jg": 2, "mid": 3, "adc": 4, "sup": 2}, "win_rate": 0.5, "preferred_line": "adc"}, {"id": "P3", "position": {"top": 4, "jg": 4, "mid": 5, "adc": 3, "sup": 3}, "win_rate": 0.7, "preferred_line": "mid"}]}
请问是否有简便方法将该JSON文件还原为原本的结构?
解决方法
有两种简便方式可以将JSON还原为包含Player对象的原始结构:
方法1:使用json.load()的object_hook自动转换
通过自定义转换函数,让json.load()在解析时自动把字典转为Player对象,适合复杂场景批量处理:
import json class Player: def __init__(self, id:str="", top:int = 0, jg:int = 0, mid:int = 0, adc:int = 0, sup:int = 0, win_rate:int = 0, preferred_line:str = "top"): self.id = id self.position = {"top": top, "jg": jg, "mid": mid, "adc": adc, "sup": sup} self.win_rate = win_rate self.preferred_line = preferred_line def dict_to_player(obj): # 判断当前字典是否为Player对应的结构 if {'id', 'position', 'win_rate', 'preferred_line'}.issubset(obj.keys()): pos = obj['position'] return Player( id=obj['id'], top=pos['top'], jg=pos['jg'], mid=pos['mid'], adc=pos['adc'], sup=pos['sup'], win_rate=obj['win_rate'], preferred_line=obj['preferred_line'] ) return obj # 读取并转换JSON with open('players.json', 'r', encoding='utf-8') as f: restored_data = json.load(f, object_hook=dict_to_player) # 验证:restored_data['Players'][0] 是 Player 实例 print(type(restored_data['Players'][0])) # 输出: <class '__main__.Player'>
方法2:手动遍历转换(逻辑直观)
如果结构简单,也可以先读取JSON为普通字典,再手动生成Player对象列表:
import json class Player: def __init__(self, id:str="", top:int = 0, jg:int = 0, mid:int = 0, adc:int = 0, sup:int = 0, win_rate:int = 0, preferred_line:str = "top"): self.id = id self.position = {"top": top, "jg": jg, "mid": mid, "adc": adc, "sup": sup} self.win_rate = win_rate self.preferred_line = preferred_line # 读取JSON数据 with open('players.json', 'r', encoding='utf-8') as f: raw_data = json.load(f) # 转换为包含Player对象的字典 restored_data = { 'Players': [ Player( id=item['id'], top=item['position']['top'], jg=item['position']['jg'], mid=item['position']['mid'], adc=item['position']['adc'], sup=item['position']['sup'], win_rate=item['win_rate'], preferred_line=item['preferred_line'] ) for item in raw_data['Players'] ] }
两种方法都能快速还原原始结构,按需选择即可。
内容的提问来源于stack exchange,提问作者Ryan Lee
相关产品推荐
相关产品推荐

