我有一个json文件,其中包含一个带有字典的对象:
{
"__class__": "monster",
"name": "Mugger",
"level": 1,
"hpTotal": 20,
"attacks": ["Sword", "Knife"],
"stats": {
"AC": 12,
"STR": 11,
"DEX": 12,
"CON": 12,
"INT": 10,
"WIS": 10,
"CHA": 10
}
}
我使用以下函数加载它:
def loadCharacters(fileLoc):
with open(fileLoc) as character_data:
data = character_data.read()
characterDictionary = json.loads(data, object_hook=decode_character)
return characterDictionary
当我通过解码器解析它时,它给出了一个基于Class的KeyError:
# Decode characters based on class
def decode_character(dct):
if dct['__class__'] == 'npc':
return character(dct["name"], dct["level"], dct["hpTotal"])
if dct['__class__'] == 'monster':
return monster(dct["name"], dct["level"], dct["hpTotal"], dct["attacks"], dct["stats"])
raise ValueError("Not a valid character dictionary")
追溯报告:
Traceback (most recent call last):
File "C:\SRC\Testing\ImportCharacters.py", line 14, in <module>
characterRoster = loadCharacters(characterFileLoc)
File "C:SRC\Characters\LoadCharacter.py", line 30, in loadCharacters
characterDictionary = json.loads(data, object_hook=decode_character)
File "C:\Python36\lib\json\__init__.py", line 367, in loads
return cls(**kw).decode(s)
File "C:\Python36\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python36\lib\json\decoder.py", line 355, in raw_decode
obj, end = self.scan_once(s, idx)
File "C:\SRC\Characters\LoadCharacter.py", line 12, in decode_character
if dct['__class__'] == 'npc':
KeyError: '__class__'
我认为它试图解析对象中的字典。 如何解析整个对象而不仅仅是子字典?
答案 0 :(得分:1)
我在这里看到的问题是你总是希望项目__class__
存在,尽管它没有发生。
使用json-data,函数decode_character
将被调用两次:
__class__
,name
,level
等AC
,STR
等我真的不知道您对代码的期望,但我会更改dct['__class__']
的{{1}},以便不会出现KeyError。
Here你可以看到一个例子。