[英]How do I add a list of dict to DynamoDB using the put_item method in boto3
我无法使用 client.put_item 方法将字典列表放入我的表中。 字典的格式为: {"name": "beef", "price":5.23}
。 像这样的列表示例如下: [{"name": "chicken", "price":6.23}, {"name": "beef", "price":5.34}, {"name": "pork", "price":8.48}]
列表大小可能会有所不同。 到目前为止我有
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
它适用于 order_id 和 order_total,但我不知道如何格式化购物车。
需要注意的几点:
parse_float=Decimal
转换为 json 并返回 object 的最简单方法。这是一个例子:
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.