json.encoder.FLOAT_REPR 已更改但没有效果

json.encoder.FLOAT_REPR changed but no effect

我正在尝试使我的 JSON 编码器转储浮点数只有 2 位小数精度。所以 '2.241' 变成 '2.24'

我在 this answer by Alex Martelli 中读到您可以覆盖 json.encoder 的默认值 FLOAT_REPR。我尝试了以下方法:

>>> import json
>>> json.encoder.FLOAT_REPR = lambda o: format(o, '.2f')

但我没有得到相同的结果:

>>> json.dumps(2.241)
'2.241'

我什至可以验证 FLOAT_REPR 是否已更改:

>>> print json.encoder.FLOAT_REPR
<function <lambda> at 0xb....>

并按预期工作:

>>> json.encoder.FLOAT_REPR(2.241)
2.24

为什么内置 JSON 模块没有使用 FLOAT_REPR,而我看到它已被覆盖并且解决方案应该根据 Alex Martelli 工作?

我在两台不同的电脑上测试过,都是 运行 Python 2.7.6 Ubuntu 14.0.4.

问题的发生是因为 c_make_encoderjson.encoder 中完成的 CPython 加速。

如果您将其设置为 None,那么 json.encoder.FLOAT_REPR 技巧就会起作用 正如这个答案中解释的一样 question:

The monkey-patch trick does not seem to work with the original simplejson module if the C speedups are installed:

我的实现可以在jsonplustypes repository.

中看到

注意:此解决方案不适用于 python 3.6+