Skip to content

Instantly share code, notes, and snippets.

@Louis-Saglio
Last active September 19, 2019 07:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Louis-Saglio/37397bd5492187c9eae481983fbb6bb5 to your computer and use it in GitHub Desktop.
Save Louis-Saglio/37397bd5492187c9eae481983fbb6bb5 to your computer and use it in GitHub Desktop.
Transform any object into dict by recursively exploring __dict__ attribute
import json
def is_iterable(obj):
try:
for _ in obj:
return True
except TypeError:
return False
def obj_to_dict(data, do_not_iter_types=(str, bytes)):
return (
{
k: obj_to_dict(v)
for k, v in dict(vars(data)).items()
if isinstance(k, str) and not (k.startswith("__") and k.endswith("__"))
}
if hasattr(data, "__dict__")
else (
data if isinstance(data, dict)
else [obj_to_dict(datum) for datum in data]
if (is_iterable(data) and not isinstance(data, do_not_iter_types))
else repr(data)
)
)
def obj_to_json(data):
return json.dumps(obj_to_dict(data), indent=2, default=str, skipkeys=True)
def rpprint(data):
print(obj_to_json(data))
if __name__ == "__main__":
# obj_to_dict(json)
a = {1:1,2:2}
rpprint(json)
@Louis-Saglio
Copy link
Author

At the 9th revision, it still does not support data structures having a reference to themselves.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment