Skip to content Skip to sidebar Skip to footer

Python SimpleJSONDecoder And Complex JSON Issue

In a unit test case that I am running, I get a KeyError exception on the 4th json object in the json text below because the piece of code responsible for decoding is looking for an

Solution 1:

Copying and pasting what you're passing to self.json_encode, and using it as an argument of json.dumps (after an import json in Python 2.6), works just fine. So it seems the bug may be in the json_encode method you're not showing us: what else does it do, besides just calling json.dumps...? (or simplejson.dumps if you're using a Python < 2.6, of course).

Edit: using json_encode = json.JSONEncoder().encode (as the OP just posted, except that's using the older simplejson as I had mentioned as a possibility) also works fine. The incomplete stack-trace also posted as part of the Q's large edit suggests that the error comes in the decoding part, perhaps through misuse of some model (can't tell, as we don't see the models) -- as the OP mentioned he's now posted a lot more info, and yet it's still not enough to debug the problem.

This strongly suggests that it would be worthwhile for the OP to try and simplify the problem a little at a time until the last incremental simplification makes the bug disappear -- that usually strongly hints at what the bug may be, but even if it doesn't, posting the tiniest way to reproduce the bug plus the info that the bug will disappear if a miniscule epsilon of code is further removes, may help "third party observers" like us all assist in the debugging. SO is not really a platform designed for collective debugging (works better for questions and answers, what it was designed for) but I don't think it breaks SO's rules to try and use it for this different purpose.


Solution 2:

Last 2 lines in traceback:

File "...j_report/src/jreport/machinestats.py", line 77, in _make_report_entry
entry_type=record['type']

You have now TWO versions of def _make_report_entry(record):

Note that the first few lines of the traceback are muttering about decode, not encode.

What has the first/original version to do with the problem?

You now say "Because my decoding function is expecting the the other objects (e.g., 'type', 'instance_id', etc.), I get a KeyError exception."

So perhaps your decoding function is being called recursively and is expected by the caller to be able to handle ANY structure, not just ones with 'type' etc.


Post a Comment for "Python SimpleJSONDecoder And Complex JSON Issue"