TypeError: __dict__ must be set to a dictionary, not a 'unicode'

TypeError: __dict__ must be set to a dictionary, not a 'unicode'

我从 git 克隆了一个库,我刚刚设法使用 savePlayerDictionary 方法。

我存储了 json 文件,一切正常。

但是

当我尝试使用 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")

您正在将播放器数据编码为 JSON,然后将整个字典映射名称编码为 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 上的 pickle module instead; it is faster and more versatile, no need to have a separate song and dance with __dict__ attributes. There is a wrapper module called shelve 甚至为对象创建一个持久化字典。