反序列化包含任意精度浮点数的json字符串,并将其序列化回来

Ric*_*cco 10 python json

Python 没有内置的任意精度浮点数。这是一个例子:

>>> float(4.4257052820783003)
4.4257052820783
Run Code Online (Sandbox Code Playgroud)

因此,无论您使用什么,都不能拥有任意精度的浮点对象。

假设我有一个包含任意精度浮点数的JSON 字符串( )。json_string = '{"abc": 4.4257052820783003}'如果我加载该字符串,Python 将剪切该数字:

>>> dct = json.loads(json_string)
>>> dct
{'abc': 4.4257052820783}
Run Code Online (Sandbox Code Playgroud)

我设法通过使用以下方法来避免这种信息丢失decimal.Decimal

>>> dct = json.loads(json_string, parse_float=Decimal)
>>> dct
{'abc': Decimal('4.4257052820783003')}
Run Code Online (Sandbox Code Playgroud)

现在,我想将此dct对象序列化为原始 JSON 格式的字符串。json.dumps(dct)显然不起作用(因为 Decimal 类型的对象不可 JSON 序列化)。我尝试子类化json.JSONEncoder并重新定义其default方法:

class MyJSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, Decimal):
            return str(o)
        return super().default(o)
Run Code Online (Sandbox Code Playgroud)

但这显然是创建一个字符串而不是数字:

>>> MyJSONEncoder().encode(dct)
'{"abc": "4.4257052820783003"}'
Run Code Online (Sandbox Code Playgroud)

如何将Decimal对象序列化为 JSON 数字(实数)而不是 JSON 字符串?换句话说,我希望编码操作返回原始json_string字符串。理想情况下不使用外部包(但仍然欢迎使用外部包的解决方案)。

这个问题当然非常相关,但我在那里找不到答案:Python JSON serialize a Decimal object

Vul*_*tyn 9

使用simplejson.dumps

如果use_decimaltrue(默认值:)True,则将decimal.Decimal以全精度本机序列化为 JSON。

import json
import simplejson
from decimal import Decimal

dct = json.loads('{"abc": 4.4257052820783003}', parse_float=Decimal)

print(dct)
print(simplejson.dumps(dct, use_decimal=True))
print(simplejson.dumps(dct)) # Also works, if Decimal in the dct.
Run Code Online (Sandbox Code Playgroud)

输出:

import json
import simplejson
from decimal import Decimal

dct = json.loads('{"abc": 4.4257052820783003}', parse_float=Decimal)

print(dct)
print(simplejson.dumps(dct, use_decimal=True))
print(simplejson.dumps(dct)) # Also works, if Decimal in the dct.
Run Code Online (Sandbox Code Playgroud)