Last active
September 19, 2019 07:06
-
-
Save Louis-Saglio/37397bd5492187c9eae481983fbb6bb5 to your computer and use it in GitHub Desktop.
Transform any object into dict by recursively exploring __dict__ attribute
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 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
At the 9th revision, it still does not support data structures having a reference to themselves.