I am writing a webapp with a Tornado backend and, of course, javascript and jquery on the frontend, so I am using the builtin json module in the standard library to serialize objects for the frontend. I had started writing a custom JSONEncoder for my classes, but then it occurred to me that I could simply write a very simple, generic object encoder:
class ObjectEncoder(json.JSONEncoder):
def default(self, obj):
return vars(obj)
It seems to be working nicely, so I wondered why this is not included in the module, and if this technique has drawbacks. I didn't experiment if it works nicely with check_circular, but I have no reason to believe it doesn't.
Any comments on my doubts? Otherwise, I suppose this technique may be useful to somebody, since I didn't find it with a search (admittedly, a quick one).
EDIT: here's an example, as simple as it gets, to show the behaviour of the json module:
>>> import json
>>> class Foo:
... def __init__(self):
... self.bar = 'bar'
...
>>> foo = Foo()
>>> json.dumps(foo)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/json/__init__.py", line 230, in dumps
return _default_encoder.encode(obj)
File "/usr/lib/python3.5/json/encoder.py", line 198, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python3.5/json/encoder.py", line 179, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <__main__.Foo object at 0x7f14660236d8> is not JSON serializable
>>> class ObjectEncoder(json.JSONEncoder):
... def default(self, obj):
... return vars(obj)
...
>>> json.dumps(foo, cls=ObjectEncoder)
'{"bar": "bar"}'
json.dumps(obj)?TypeError: <... instance at ...> is not JSON serializable. This seems to be by design, since it is explicitly stated in the documentation, I would just like to understand why it is so, and if there are complication which I do not see.