問題描述
我在 python 2.6 中使用標準 json 模塊 來序列化浮點列表.但是,我得到這樣的結果:
I am using the standard json module in python 2.6 to serialize a list of floats. However, I'm getting results like this:
>>> import json
>>> json.dumps([23.67, 23.97, 23.87])
'[23.670000000000002, 23.969999999999999, 23.870000000000001]'
我希望浮點數的格式只有兩位小數.輸出應如下所示:
I want the floats to be formated with only two decimal digits. The output should look like this:
>>> json.dumps([23.67, 23.97, 23.87])
'[23.67, 23.97, 23.87]'
我嘗試定義自己的 JSON 編碼器類:
I have tried defining my own JSON Encoder class:
class MyEncoder(json.JSONEncoder):
def encode(self, obj):
if isinstance(obj, float):
return format(obj, '.2f')
return json.JSONEncoder.encode(self, obj)
這適用于唯一的浮動對象:
This works for a sole float object:
>>> json.dumps(23.67, cls=MyEncoder)
'23.67'
但嵌套對象失敗:
>>> json.dumps([23.67, 23.97, 23.87])
'[23.670000000000002, 23.969999999999999, 23.870000000000001]'
我不想有外部依賴,所以我更喜歡堅持使用標準的 json 模塊.
I don't want to have external dependencies, so I prefer to stick with the standard json module.
我怎樣才能做到這一點?
How can I achieve this?
推薦答案
注意:這不在任何最新版本的 Python 中都有效.
Note: This does not work in any recent version of Python.
不幸的是,我認為您必須通過猴子修補來做到這一點(在我看來,這表明標準庫 json
包中的設計缺陷).例如,這段代碼:
Unfortunately, I believe you have to do this by monkey-patching (which, to my opinion, indicates a design defect in the standard library json
package). E.g., this code:
import json
from json import encoder
encoder.FLOAT_REPR = lambda o: format(o, '.2f')
print(json.dumps(23.67))
print(json.dumps([23.67, 23.97, 23.87]))
發射:
23.67
[23.67, 23.97, 23.87]
如你所愿.顯然,應該有一種架構化的方式來覆蓋 FLOAT_REPR
,這樣如果你愿意,浮點的每一個表示都在你的控制之下;但不幸的是,這不是 json
包的設計方式:-(.
as you desire. Obviously, there should be an architected way to override FLOAT_REPR
so that EVERY representation of a float is under your control if you wish it to be; but unfortunately that's not how the json
package was designed:-(.
這篇關于使用標準 json 模塊格式化浮點數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!