MasoniteFramework / orm

Masonite ORM is a beautiful Python ORM. It's also a nearly drop in replacement of the Orator ORM
https://orm.masoniteproject.com
MIT License
161 stars 47 forks source link

JSONCast Force conversion to str for unhandled types #818

Closed circulon closed 1 year ago

circulon commented 1 year ago

This fixes issues when casting types like Decimal to JSON throwing a TypeError

BSN4 commented 1 year ago

better to convert it to float

class JSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Decimal):
            return float(obj)
        return json.JSONEncoder.default(self, obj)
circulon commented 1 year ago

better to convert it to float

class JSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Decimal):
            return float(obj)
        return json.JSONEncoder.default(self, obj)

@if4lcon No you miss the point, Decimal is just an example and is not the only use case here. Other examples are UUID so by defining the default any obect that is not directly JSON encodable will be asked for its str repr which is encodable.

Also converting a Decimal to float loses specificity of the value so that would not be ideal, but that is another conversation

I hope this clarifies things for you