I am not able to serialize a custom object in python 3 . Below is the explanation and code
packages= []
data = {
"simplefield": "value1",
"complexfield": packages,
}
where packages is a list of custom object Library
.
Library object
is a class as below (I have also sub-classed json.JSONEncoder
but it is not helping )
class Library(json.JSONEncoder):
def __init__(self, name):
print("calling Library constructor ")
self.name = name
def default(self, object):
print("calling default method ")
if isinstance(object, Library):
return {
"name": object.name
}
else:
raiseExceptions("Object is not instance of Library")
Now I am calling json.dumps(data)
but it is throwing below exception.
TypeError: Object of type `Library` is not JSON serializable
It seems "calling default method"
is not printed meaning, Library.default
method is not called
Can anybody please help here ?
I have also referred to Serializing class instance to JSON but its is not helping much