转换嵌套字典/列表中的 Decimal.decimalvalues

Tho*_*son 2 python dictionary nested mongodb

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

以前,您可以使用 来执行此操作son_manipulator,但现在已弃用

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

Jos*_*lls 5

与 Amazon 的 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
Run Code Online (Sandbox Code Playgroud)