简体   繁体   中英

Python Parsing Dictionary within a Dictionary from JSON

I have a json file that contains an object with a dictionary within it:

{
   "__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
   }
}

I load it with the following function:

def loadCharacters(fileLoc):
    with open(fileLoc) as character_data:
        data = character_data.read()
        characterDictionary = json.loads(data, object_hook=decode_character)
    return characterDictionary 

When i parse it through my decoder it is giving me a KeyError based on Class:

# 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 report:

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__'

I think that it is trying to parse the dictionary within the object. How do i get the whole object parsed and not just the sub dictionary?

The problem I see here is that you always expect the item __class__ to exist although it does not happen.

With the json-data you provide the function decode_character will be called twice:

  • One with the root json-object data. With keys __class__ , name , level , etc.
  • Once more with the inner json-object data. With keys AC , STR , etc.

I do not really know what you expect from you code but I would change the dct['__class__'] for dct.get('__clas__') so that a KeyError is not arisen.

Here you can see an example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM