如何在Python中将参数传递给自定义JSONEncoder default()函数 [英] How to pass parameters to a custom JSONEncoder default() function in Python
问题描述
在我的Flask应用程序中,我使用了一个自定义的JSONEncoder
,该序列将decimal.Decimal
对象进行序列化,并四舍五入到两个位置.
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)
prec
参数使我可以更改舍入的精度.默认为两个地方.我想偶尔调用json.dumps
并将其传递给prec
参数,这样我就可以强制将decimal.Decimal
对象舍入到4位.
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)
但是当我这样做时,JSON模块会抛出:
But when I do this, the JSON module throws:
TypeError: __init__() got an unexpected keyword argument 'prec'
可以在这里做我想做的事情吗?我不明白为什么JSON模块对**kwargs
做任何事情.我可以强迫它忽略它们吗?
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?
推荐答案
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)
这篇关于如何在Python中将参数传递给自定义JSONEncoder default()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!