Skip to content

Conversation

@circulon
Copy link
Contributor

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

@circulon circulon changed the title Force conversion to str for unhandled types JSONCast Force conversion to str for unhandled types Oct 20, 2022
@BSN4
Copy link
Contributor

BSN4 commented Oct 21, 2022

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
Copy link
Contributor Author

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

Copy link
Member

@josephmancuso josephmancuso left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks fine to me

@josephmancuso josephmancuso merged commit 19437ac into MasoniteFramework:2.0 Oct 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants