【问题标题】:Convert Decimal.decimalvalues in nested dict/list转换嵌套字典/列表中的 Decimal.decimal 值
【发布时间】:2026-01-28 01:40:01
【问题描述】:

我有一个对象,它是dictlist、常规数据类型和decimal.Decimal 的嵌套组合。我想用 PyMongo 将此对象插入 MongoDB。 PyMongo 拒绝插入Decimal.decimal,所以我想将我所有的Decimal.decimal 转换为string

以前,您可以使用 son_manipulator 执行此操作,但现在是 deprecated

如何有效地将嵌套数据结构中的所有decimal.Decimal 对象转换为strings?

【问题讨论】:

  • 我承认懒得检查,但“它是否已弃用”?文档没有这样标记。我知道已弃用的 eval 之类的东西已明确标记。因此,如果使用实际上返回了弃用警告,则应修改文档。如果不是,那么我想知道您为什么认为它已被弃用。
  • 对不起,我链接到了错误的页面。它在api.mongodb.com/python/current/examples/custom_type.html 被标记为已弃用。编辑修复
  • 好地方。考虑到用法,弃用当然是有道理的。可能应该是一个 JIRA 来向original documentation page you referenced 添加一个明确的通知。

标签: python mongodb dictionary nested


【解决方案1】:

与亚马逊的 DynamoDB 和 boto3 完全相同。

def replace_decimals(obj):
    if isinstance(obj, list):
        for i in xrange(len(obj)):
            obj[i] = replace_decimals(obj[i])
        return obj
    elif isinstance(obj, dict):
        for k in obj.iterkeys():
            obj[k] = replace_decimals(obj[k])
        return obj
    elif isinstance(obj, decimal.Decimal):
        return str(obj)
        # In my original code I'm converting to int or float, comment the line above if necessary.
        if obj % 1 == 0:
            return int(obj)
        else:
            return float(obj)
    else:
        return obj

【讨论】: