Created
February 18, 2015 18:01
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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