Flask不停JSON格式化decim

2024-09-29 21:34:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Flask untillet 0.17作为API。API有几个字段是小数。我可以通过安装simplejson成功地返回小数点,如这里所述:https://stackoverflow.com/a/15224186/1753891。在

但是,当我有一个十进制字段是0时,这个值是用科学符号表示的,比如0E-8。我想改为返回0.00000000。在

我正在尝试类似的方法,但无法使其发挥作用。0仍然以科学记数法返回。在

class DecimalJSONEncoder(json.JSONEncoder):
    # Try to format the decimal
    # EDIT: but am now realizing that this doesn't work
    # It was serializing the decimal at all because I had 
    # simplejson installed.
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return format(str(o), '.8f')
        return super(DecimalJSONEncoder, self).default(o)


def init_app(app):
    # .....
    # Use the Flask-Restless postprocessor to format.
    def postprocesor(result, **kw):
        json.dumps(result, cls=DecimalJSONEncoder)

当小数为零时,如何强制小数为0.00000000?在


Tags: thetoselfapijsonformatdefaultflask

热门问题