2

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

8
  • 2
    thousands of classes or instances? Commented Jun 15, 2018 at 0:14
  • Also see answers to Making object JSON serializable with regular encoder. Commented Jun 15, 2018 at 1:21
  • BTW, every object in Python does not necessarily have a __dict__. Objects of type int don't for example. Commented Jun 15, 2018 at 1:38
  • @EvgenyPogrebnyak, classes. This is a generated SDK. It better not allocate thousands of instances, wasting the consumer developers memory. Commented Jun 15, 2018 at 14:47
  • @martineau, this looks promising, I'll respond with my results later today. Commented Jun 15, 2018 at 14:47

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.