Skip to content

Instantly share code, notes, and snippets.

@jpadilla
Created September 27, 2011 19:52
Show Gist options
  • Save jpadilla/1246043 to your computer and use it in GitHub Desktop.
Save jpadilla/1246043 to your computer and use it in GitHub Desktop.
def todict(obj, classkey=None):
if isinstance(obj, dict):
for k in obj.keys():
obj[k] = todict(obj[k], classkey)
return obj
elif hasattr(obj, "__iter__"):
return [todict(v, classkey) for v in obj]
elif hasattr(obj, "__dict__"):
data = dict([(key, todict(value, classkey))
for key, value in obj.__dict__.iteritems()
if not callable(value) and not key.startswith('_')])
if classkey is not None and hasattr(obj, "__class__"):
data[classkey] = obj.__class__.__name__
return data
else:
return obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment