I have a python module that will generate thousands of classes that will be used for http calls.
These classes must be converted to JSON objects to make the call.
When I try a simple example like:
from json import JSONEncoder import json class BaseObject: pass class MyEncoder(JSONEncoder): def default(self, o): if isinstance(o, BaseObject): return JSONEncoder.default(self, dict(o.__dict__)) class foo(BaseObject): def __init__(self): self.bar = bar() class bar(BaseObject): pass MyEncoder().encode(foo()) I get a stack with the error:
File "f:\sdks\Python\testA.py", line 27, in <module> MyEncoder().encode(foo()) File "C:\Users\{user}\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Users\{user}\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "f:\sdks\Python\testA.py", line 11, in default return JSONEncoder.default(self, dict(o.__dict__)) File "C:\Users\{user}\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 180, in default o.__class__.__name__) TypeError: Object of type 'dict' is not JSON serializable I thought every object in Python was essentially a dict which should be a valid single tiered JSON object. But this doesn't seem to be the case?
The main problem is that "dict" isn't serializable (clearly stated in the failure output), which documentation explicitly states that dict is serializable to a JSON object https://docs.python.org/3/library/json.html#json.JSONEncoder
__dict__. Objects of typeintdon't for example.