我从git克隆了一个库,我只是设法使用savePlayerDictionary
方法。
我存储了json文件,一切看起来都很好。
BUT
当我尝试使用loadPlayerDictionary时,我收到错误:
TypeError: __dict__ must be set to a dictionary, not a 'unicode'
我的代码:
def savePlayerDictionary(playerDictionary, pathToFile):
"""
Saves player dictionary to a JSON file
"""
player_json = {name: player_data.to_json() for name, player_data in playerDictionary.items()}
json.dump(player_json, open(pathToFile, 'wb'), indent=0)
def loadPlayerDictionary(pathToFile):
"""
Loads previously saved player dictionary from a JSON file
"""
result = {}
with open(pathToFile, "r") as f:
json_dict = json.load(f)
for player_name in json_dict:
parsed_player = Player(None,None,False)
parsed_player.__dict__ = json_dict[player_name]
result[player_name] = parsed_player
return result
其中player_data.to_json()
实现为:
def to_json(self):
return json.dumps(self.__dict__)
我运行的代码是:
get_ipython().magic(u'matplotlib inline')
import basketballCrawler as bc
import matplotlib.pyplot as plt
players = bc.loadPlayerDictionary("myJson.json")
答案 0 :(得分:1)
您正在将播放器数据编码为JSON,然后将整个字典映射名称再次编码为JSON 再次,从而为该映射的值生成双重编码的JSON数据。
解码时,您只解码了名称 - 数据映射,而不是每个播放器的数据。您需要单独解码:
parsed_player = Player(None,None,False)
parsed_player.__dict__ = json.loads(json_dict[player_name])
如果你没有在to_json()
中编码,那就更容易了:
def to_json(self):
return vars(self)
(我使用vars()
function作为更清晰的函数来获取相同的字典。)
如果您所做的只是保留播放器数据,请考虑使用pickle
module;它更快,更通用,不需要单独的歌曲和舞蹈与__dict__
属性。有一个名为shelve
的包装器模块构建在pickle
上,甚至可以为对象创建一个持久化字典。