2

In my Flask application, I use a custom JSONEncoder that serializes decimal.Decimal objects rounded to two places.

class MyJsonEncoder(JSONEncoder):

    def default(self, obj, prec=2):

        if isinstance(obj, Decimal):
            return str(obj.quantize(Decimal('.'+'0'*(prec-1)+'2')))
        else:
            return JSONEncoder.default(self, obj)

The prec parameter lets me change the precision of the rounding. It defaults to two places. I want to occasionally call json.dumps and pass it a prec parameter so I can force the decimal.Decimal objects to round to 4 places instead.

json_string = json.dumps(some_data, prec=4)

But when I do this, the JSON module throws:

TypeError: __init__() got an unexpected keyword argument 'prec'

Is it possible to do what I'm trying here? I don't understand why the JSON module is doing anything with the **kwargs. Can I force it to ignore them?

1 Answer 1

3
class MyJsonEncoder(JSONEncoder):

    def __init__(self, prec=2, **kwargs):
        super(MyJsonEncoder, self).__init__(**kwargs)
        self.prec = prec

    def default(self, obj):
        prec = self.prec
        ...

MyJsonEncoder(prec=4).encode(some_data)
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for editing your response. Your initial response sent me in the right direction and I ended up writing something exactly like what you have above. Works like a charm!
How would you use that in a json.dump call to serialize to file with indentation etc.?
@Campa using json.dump(..., cls=MyJsonEncoder).
right, but this way you cannot parameterize the value of prec, right?
@Campa json.dump(..., cls=MyJsonEncoder, prec=4)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.