我正在嘗試序列化字典playersElo以將其作為/從 JSON 保存/加載。但因為它不是一個可序列化的物件,我找不到辦法做到這一點。
playersElo={} # dictionnary of {<int> : <PlayerElo>}
playersElo[1] = PlayerElo()
playersElo[2] = PlayerElo()
...
class PlayerElo:
"""
A class to represent a player in the Elo Rating System
"""
def __init__(self, name: str, id: str, rating):
self.id = id
self.name = name
# comment the 2 lines below in order to start with a rating associated
# to current player rank
self.eloratings = {0: 1500}
self.elomatches = {0: 0}
self.initialrating = rating
uj5u.com熱心網友回復:
也許這可以成為您的起點。序列化器__dict__從物件中獲取屬性并創建一個新的 dict-of-dicts,然后將其寫入 JSON。解串器創建一個虛擬物件,然后在__dict__進入的程序中更新。
import json
class PlayerElo:
"""
A class to represent a player in the Elo Rating System
"""
def __init__(self, name: str, id: str, rating):
self.id = id
self.name = name
self.eloratings = {0: 1500}
self.elomatches = {0: 0}
self.initialrating = rating
playersElo={} # dictionnary of {<int> : <PlayerElo>}
playersElo[1] = PlayerElo('Joe','123',999)
playersElo[2] = PlayerElo('Bill','456',1999)
def serialize(ratings):
newdict = {i:j.__dict__ for i,j in ratings.items()}
json.dump( newdict, open('x.json','w') )
def deserialize():
o = json.load(open('x.json'))
pe = {}
for k,v in o.items():
obj = PlayerElo('0','0',0)
obj.__dict__.update( v )
pe[int(k)] = obj
return pe
print(playersElo)
serialize( playersElo )
pe = deserialize( )
print(pe)
uj5u.com熱心網友回復:
您可以擴展json.JSONEncoder以處理您的類的實體。模塊的檔案中有一些示例,但這里有一個為什么要和你的PlayerElo班級一起做。
注意:另請參閱我對使用常規編碼器制作物件 JSON 序列化問題的回答,以獲得更通用的方法。
import json
class PlayerElo:
""" A class to represent a player in the Elo Rating System. """
def __init__(self, name: str, id: str, rating):
self.id = id
self.name = name
# comment the 2 lines below in order to start with a rating associated
# to current player rank
self.eloratings = {0: 1500}
self.elomatches = {0: 0}
self.initialrating = rating
class MyJSONEcoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, PlayerElo):
return dict(type='PlayerElo', name=obj.name, id = obj.id,
rating=obj.initialrating)
return super().default(obj)
playersElo={} # dictionnary of {<int> : <PlayerElo>}
playersElo[1] = PlayerElo('Bob', 'thx1138', 4)
playersElo[2] = PlayerElo('Sue', 'p-138', 3)
from pprint import pprint
my_encoder = MyJSONEcoder()
pprint(my_encoder.encode(playersElo))
這是它生成并列印的 JSON 字串:
('{"1": {"type": "PlayerElo", "name": "Bob", "id": "thx1138", "rating": 4}, '
'"2": {"type": "PlayerElo", "name": "Sue", "id": "p-138", "rating": 3}}')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/397736.html
