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?