I\'m dealing with an API that unfortunately is returning malformed (or \"weirdly formed,\" rather -- thanks @fjarri) JSON, but on the positive side I think it may be an opportun
Your main issue is that your object_hook
function should not be recursing. json.loads()
takes care of the recursing itself and calls your function every time it finds a dictionary (aka obj
will always be a dictionary). So instead you just want to modify the problematic keys and return the dict -- this should do what you are looking for:
def flatten_hook(obj):
for key, value in obj.iteritems():
if isinstance(value, basestring):
try:
obj[key] = json.loads(value, object_hook=flatten_hook)
except ValueError:
pass
return obj
pprint(json.loads(my_input, object_hook=flatten_hook))
However, if you know the problematic (double-encoded) entry always take on a specific form (e.g. key == 'timezone_id'
) it is probably safer to just call json.loads()
on those keys only, as Matt Anderson suggests in his answer.