Skip to content

Instantly share code, notes, and snippets.

@bryder
Created May 16, 2017 21:08
Show Gist options
  • Save bryder/3ad1387dd403b74e9c520317d6224fc4 to your computer and use it in GitHub Desktop.
Save bryder/3ad1387dd403b74e9c520317d6224fc4 to your computer and use it in GitHub Desktop.
An object encoder that will recursively encode arbitrary python objects
# This is a minor modification of http://stackoverflow.com/a/35483750/1543555
class JSONObjectEncoder(json.JSONEncoder):
def default(self, obj):
if hasattr(obj, "to_json"):
return self.default(obj.to_json())
else:
if isinstance(obj, dict):
return obj
elif isinstance(obj, datetime.datetime):
return obj.isoformat()
elif isinstance(obj, datetime.timedelta):
return str(obj)
elif isinstance(obj, set):
return list(obj)
else:
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment