I am trying to make a custom JSON encoder and I ran into this problem I don't understand.
I basically followed the instructions of the official documentation
Encoding a dictionary is clearly possible with the standard JSON encoder. But if I convert the custom object to a dict and pass it to the default encoder, I get an: TypeError: Object of type dict is not JSON serializable
.
Clearly there is something I am missing here. Can someone explain to me the behavior of the toy example below?
import json
class Klass():
def __init__(self,number):
self.number = number
def __dict__(self):
return {"number": self.number}
class CustomEncoder(json.JSONEncoder):
def default(self,obj):
if isinstance(obj,Klass):
obj=obj.__dict__()
return json.JSONEncoder.default(self, obj)
json.dumps({"number" : 10}) # works
json.dumps({"number" : 10},cls=json.JSONEncoder) # works
json.dumps({"number" : 10},cls=CustomEncoder) # works
json.dumps(Klass(10).__dict__(), cls=CustomEncoder) # works
json.dumps({"Test":Klass(10).__dict__()}, cls=CustomEncoder) #works
try:
json.dumps(Klass(10), cls=CustomEncoder) # TypeError: Object of type dict is not JSON serializable
except TypeError:
print("Error 1")
# this is my end goal to encode a dict of objects
try:
json.dumps({"Test":Klass(10)}, cls=CustomEncoder) # TypeError: Object of type dict is not JSON serializable
except TypeError:
print("Error 2")
# this works but clearly it shows me the Custom encoder is not doing what I think it does
encode_hack = {k: v.__dict__() for k, v in {"Test":Klass(10)}.items()}
json.dumps(encode_hack)