[英]JSON serialization of dictionary with complex objects
我正在嘗試序列化字典playersElo
以將其作為/從 JSON 保存/加載。 但由於它不是可序列化的 object ,所以我找不到辦法。
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
也許這可以成為您的起點。 序列化程序從 object 中獲取__dict__
屬性並創建一個新的 dict-of-dicts,然后將其寫入 JSON。 解串器創建一個虛擬 object,然后在進入的過程中更新__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( o )
pe[int(k)] = obj
return pe
print(playersElo)
serialize( playersElo )
pe = deserialize( )
print(pe)
您可以擴展json.JSONEncoder
來處理 class 的實例。 模塊文檔中有示例,但這里有一個使用PlayerElo
class 的原因。
注意:另請參閱我對使用常規編碼器可序列化 object 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}}')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.