Python: converting class objects to JSON - object is not JSON serializable
Solution 1:
You wish the encoder to support both Decimal
and dataclass
es. You can do it like so:
import dataclasses, json
class JSONEncoder(json.JSONEncoder):
def default(self, o):
if dataclasses.is_dataclass(o):
return dataclasses.asdict(o)
if isinstance(obj, Decimal):
return str(obj)
return super().default(o)
json.dumps(foo, cls=JSONEncoder)