简体   繁体   English

如何在Python中将参数传递给自定义JSONEncoder default()函数

[英]How to pass parameters to a custom JSONEncoder default() function in Python

In my Flask application, I use a custom JSONEncoder that serializes decimal.Decimal objects rounded to two places. 在我的Flask应用程序中,我使用了一个自定义的JSONEncoder ,该序列化了decimal.Decimal对象。

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. prec参数使我可以更改舍入的精度。 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.dumps并将其传递给prec参数,这样我就可以强制将decimal.Decimal对象舍入到4位。

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

But when I do this, the JSON module throws: 但是,当我这样做时,JSON模块会抛出:

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 . 我不明白为什么JSON模块**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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM