包含小数的 Python dict 转换为 JSON

Vin*_*eet 5 python json

可能的重复:
Python JSON 序列化 Decimal 对象

任务:将包含混合数据类型(整数/字符串/小数/...)作为值的字典转换为 JSON 数组。

我知道如何将 python 字典转换为 JSON:

D = {key1:val1, key2,val2}
import json
jD = json.dumps(D)
Run Code Online (Sandbox Code Playgroud)

我还知道十进制值必须转换为字符串,否则 python 会抛出“十进制不是 json 可序列化”的错误。

所以我需要遍历字典来查找数据类型。

for key in D.keys():
    if type(key) == '<class "decimal.Decimal">': ## this is erroneous. pl. suggest correction
    D[key] = str(D[key])
Run Code Online (Sandbox Code Playgroud)

但这种编程涉及手工编码和硬编码。

如果我得到嵌套字典结构,则再次需要硬编码(这是错误的)。

是否有其他方法/技巧可以从 dict 中的任何数据类型获取 JSON 数组?

Mar*_*mro 3

为什么不子类化 JSONEncoder?它简单干净:

class DecimalEncoder(json.JSONEncoder):
    def _iterencode(self, o, markers=None):

        if isinstance(o, decimal.Decimal):  # isinstance() is better than type(), because it handles inheritance
            return (str(o) for o in [o])

        return super(DecimalEncoder, self)._iterencode(o, markers)
Run Code Online (Sandbox Code Playgroud)