Created
December 5, 2019 03:55
-
-
Save KentaYamada/5d3c17827065ddf6b9d465edf9297859 to your computer and use it in GitHub Desktop.
Convert object to json string
This file contains hidden or 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 json_dumps_handler(data): | |
has_dict = isinstance(data, object) and hasattr(data, '__dict__') | |
if not has_dict: | |
raise TypeError() | |
return data.__dict__ | |
class Root: | |
def a(self): | |
return True | |
class Node: | |
pass | |
root = Root() | |
root.ham = 1 | |
root.spam = 'hoge' | |
root.node = Node() | |
root.nodes = (Node(),Node(),Node()) | |
print(json.dumps(root, default=json_dumps_handler, indent=2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment