我正在使用 Flask-Restless 0.17 作为 API。API 有几个小数字段。我可以通过安装 simplejson 成功返回小数,如下所述:https ://stackoverflow.com/a/15224186/1753891 。
但是,当我有一个为 0 的十进制字段时,该值采用科学计数法,例如0E-8
. 我想改为 return 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
为零时?