不了解任何预构建的内容,但是如果您的对象足够简单,则可以编写一个。覆盖JSONEnprer中的默认方法以查看inspect.getmembers(obj)(inspect是获取中的属性集的更易读的方法
__dict__)。
#!/usr/bin/env python3import inspectfrom json import JSonEnprerclass TreeNode: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = rightclass ObjectJSonEnprer(JSONEnprer): def default(self, reject): is_not_method = lambda o: not inspect.isroutine(o) non_methods = inspect.getmembers(reject, is_not_method) return {attr: value for attr, value in non_methods if not attr.startswith('__')}if __name__ == '__main__': tree = TreeNode(42, TreeNode(24), TreeNode(242), ) print(ObjectJSonEnprer().enpre(tree))更新: @Alexandre Deschamps说,对于某些输入而言,isroutine比方法更有效。



