When attempting to serialize a class to JSON in python you could try to call json.dumps(my_class_instance)
. However, this will raise TypeError: Object of type MyClass is not JSON serializable
. There are many different suggestions on how to get around this (i.e. json.dumps(instance.__dict__)
, json.dumps(instance, default=...)
, etc.). However, often times you cannot control the call to dumps()
(i.e. in a web server application that automatically serializes objects to JSON as part of the request/response flow). Is there a way to implement a dunder method or similar on MyClass
such that a call to json.dumps(my_class_instance)
will succeed? Implementing __dict__
does not suffice.
Asked
Active
Viewed 20 times
0

jlhasson
- 1,516
- 1
- 15
- 23
-
Did you try reading the documentation for the `json` module? Specifically, for [the encoder class](https://docs.python.org/3/library/json.html#json.JSONEncoder)? – Karl Knechtel Jun 01 '22 at 15:36
-
If your framework doesn't allow you to control the call to `json.dumps` explicitly, it should provide its own way to ensure an instance can be encoded. (For example, the Flask-JSON extension for Flask apps.) – chepner Jun 01 '22 at 15:38
-
IIRC the `json.JSONEncoder` class is to extend the functionality of `json.dumps`, which I don't have access to. @chepner thanks for the pointer, I am using FastAPI and it appears they have something similar - https://fastapi.tiangolo.com/tutorial/encoder/. Still, some native way to extend this functionality to classes would be useful imo. – jlhasson Jun 02 '22 at 00:01