Skip to content

Instantly share code, notes, and snippets.

@imankulov
Created February 18, 2015 18:01
Show Gist options
  • Save imankulov/da3945a04209a34bb7c5 to your computer and use it in GitHub Desktop.
Save imankulov/da3945a04209a34bb7c5 to your computer and use it in GitHub Desktop.
dictify.py -- extract "__dict__" contents from all objects recursively, and build a tree of them.
import json
def dictify(obj):
"""
Recursively find all dicts in a stricture, and convert them to attr dict
"""
if isinstance(obj, (list, tuple, set)):
return obj.__class__([dictify(item) for item in obj])
if isinstance(obj, dict):
return {dictify(k): dictify(v) for k, v in obj.items()}
if hasattr(obj, '__dict__'):
ret = dictify(obj.__dict__)
ret['__class__'] = '%s.%s' % (obj.__module__, obj.__class__.__name__)
return ret
return obj
def dictify_dump(obj):
with open('/tmp/dictify.json', 'w') as fd:
json.dump(dictify(obj), fd)
print "explore this dump on http://jsonviewer.stack.hu/"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment