Created
December 10, 2018 13:05
-
-
Save wuftymerguftyguff/cb93f0a4a3affba132ad70a84e50a19e to your computer and use it in GitHub Desktop.
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
# Class to JSON encode nested and awkward python objects | |
import json | |
import inspect | |
class ObjectEncoder(json.JSONEncoder): | |
def default(self, obj): | |
if hasattr(obj, "to_json"): | |
return self.default(obj.to_json()) | |
elif hasattr(obj, "__dict__"): | |
d = dict( | |
(key, value) | |
for key, value in inspect.getmembers(obj) | |
if not key.startswith("__") | |
and not inspect.isabstract(value) | |
and not inspect.isbuiltin(value) | |
and not inspect.isfunction(value) | |
and not inspect.isgenerator(value) | |
and not inspect.isgeneratorfunction(value) | |
and not inspect.ismethod(value) | |
and not inspect.ismethoddescriptor(value) | |
and not inspect.isroutine(value) | |
) | |
return self.default(d) | |
return obj |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment