""" A simple way to encode a MyObj instance is to define a function to convert an unknown type to a known type. This function does not need to do the encoding; it should simply convert one type of object to another. """ # import sys # sys.path.append('.') import json_myobj import json obj = json_myobj.MyObj('instance value goes here') print('First attempt') try: print(json.dumps(obj)) except TypeError as err: print('ERROR:', err) def convert_to_builtin_type(obj): print('default(', repr(obj), ')') # Convert objects to a dictionary of their representation. d = { '__class__': obj.__class__.__name__, '__module__': obj.__module__, } d.update(obj.__dict__) return d
# -*- coding: utf-8 -*- import json import json_myobj class MyEncoder(json.JSONEncoder): def default(self, obj): print('default(', repr(obj), ')') # Convert objects to a dictionary of their representation d = { '__class__': obj.__class__.__name__, '__module__': obj.__module__, } d.update(obj.__dict__) return d obj = json_myobj.MyObj('internal data') print(obj) print(MyEncoder().encode(obj))