[英]How do I add a list of dict to DynamoDB using the put_item method in boto3
I am having trouble using the client.put_item method to put a list of dicts to my table.我无法使用 client.put_item 方法将字典列表放入我的表中。 The dict is in the form: {"name": "beef", "price":5.23}
.字典的格式为: {"name": "beef", "price":5.23}
。 An example of a list like this is: [{"name": "chicken", "price":6.23}, {"name": "beef", "price":5.34}, {"name": "pork", "price":8.48}]
where the list size could vary .像这样的列表示例如下: [{"name": "chicken", "price":6.23}, {"name": "beef", "price":5.34}, {"name": "pork", "price":8.48}]
列表大小可能会有所不同。 So far I have到目前为止我有
def create_order(order_id, cart, total):
dynamodb = boto3.client('dynamodb')
table = 'Orders'
response = dynamodb.put_item(TableName=table,
Item={
'order_id': {"S":order_id},
'order_total': {"N":str(total)},
'cart':{"L":cart}
}
)
return response
It works with order_id and order_total, but I can't figure out how to format the cart.它适用于 order_id 和 order_total,但我不知道如何格式化购物车。
Couple of things to Note:需要注意的几点:
parse_float=Decimal
.浮点数是不可接受的(未解决的问题),因此,使用parse_float=Decimal
转换为 json 并返回 object 的最简单方法。Here is an example:这是一个例子:
import json
import boto3
from decimal import Decimal
dynamodb = boto3.resource('dynamodb',region_name='us-east-1')
table = dynamodb.Table('Orders')
order_id = "1000"
total = 100
cartBefore = [{"name": "chicken", "price":6.23}, {"name": "beef", "price":5.34}, {"name": "pork", "price":8.48}]
cart = json.loads(json.dumps(cartBefore), parse_float=Decimal)
response = table.put_item(
Item={
'id': '10',
'order_id': order_id,
'order_total': total,
'cart': cart
}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.