Search code examples
pythonjsonexceptionexcept

Why is this except being called? - Python


I have a method that checks a JSON payload for JSON decoding errors, and KeyErrors. For some reason, the except statement with the KeyError is getting called, but then shows there was in fact, no KeyError as the object is None. Here is the code:

    try:
        test_data = simplejson.loads(self.raw_data) # Loads the data in a dict to test for the right fields
        test_data["test"]

    except simplejson.decoder.JSONDecodeError as jsonErr:
        print 'JSON Malform Error: ', jsonErr
        pass
        return False

    except KeyError as keyErr:
        print 'JSON Validation Error: ', keyErr
        pass

Solution

  • The KeyError is probably raised by simplejson.loads and the offending key may really be None. Not enough context to say more. If you give the traceback as asked, it will help greatly.