Python/Boto3:不支持浮点类型。请改用十进制类型。

26

我正在使用Python 3.7将数据存储在DynamoDB数据库中,但是在尝试向数据库写入项目时遇到了以下错误信息:

Float types are not supported. Use Decimal types instead.

我的代码:

ddb_table = my_client.Table(table_name)

with ddb_table.batch_writer() as batch:
    for item in items:
        item_to_put: dict = json.loads(json.dumps(item), parse_float=Decimal)

        # Send record to database.
        batch.put_item(Item=item_to_put)

"items"是一个Python字典列表。如果我打印出"item_to_put"字典的类型,它们都是字符串类型。

提前感谢您的任何帮助。


item_to_put 究竟是什么? - Marcin
@Marcin 这是一个包含我想要添加到 DynamoDB 表中的项目的字典。 - GarlicBread
4个回答

45

将所有的浮点数转换为Decimal

import json
from decimal import Decimal
item = json.loads(json.dumps(item), parse_float=Decimal)

table.put_item(
    Item=item
)

哼,我收到了TypeError('十进制类型的对象不可JSON序列化') - Alexander Goldabin
2
这似乎与原帖中的代码没有任何区别。 - GarlicBread

7

我遇到了同样的问题,结果发现Python传递的字符串参数不是字符串。当我用str()将所有项包装起来时,问题就解决了。


是的,我不得不做这样的事情,这并不理想:item_to_put: dict = {} for item_key in item: item_to_put[item_key] = str(item[item_key]) - GarlicBread
3
尽可能保留类型。请查看 M S R 的解决方案。 - Ivailo Bardarov

0
在表达式之前添加:from decimal import Decimal。这应该解决问题。

0

我也遇到了同样的问题。在我的情况下,是因为我的某些记录没有特定的键,而该键默认情况下会被自动添加为NaN(我猜是这样?)。在运行batch.put_item之前,我添加了一些简单的逻辑来检查该键是否是列表,并将其设置为空列表,这似乎满足了Dynamo beast。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接