当我具有以下形式的JSON数据时,我无法将JSON数据持久化到dynamo DB中。可以有一个或多个对象,如下所示。如果需要,请格式化JSON数据。
{
"skuId":34,
"description":"Raymonds",
"price":4999,
"product":"Shirt"
},
"skuId":35,
"description":"Wrogn",
"price":1999,
"product":"T-Shirt"
},
"skuId":36,
"description":"Peter England",
"price":3999,
"product":"Trouser"
}
采用以下格式时,我可以保留数据。要求是我不想将数据包含在“产品”中,并使用上面的表格来保留它。
{
"Products":[
{
"skuId":95,
"description":"Raymonds",
"price":2999,
"product":"Shirt"
},
{
"skuId":96,
"description":"Raymonds",
"price":3999,
"product":"Shirt"
},
{
"skuId":97,
"description":"Raymonds",
"price":6999,
"product":"Shirt"
}]
}
这是我的代码,使用它我可以保留上述形式的数据。
import json
import boto3
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
s3_client = boto3.client('s3')
dynamodb = boto3.resource('dynamodb')
def lambda_handler(event, context):
bucket = event['Records'][0]['s3']['bucket']['name']
json_file_name = event['Records'][0]['s3']['object']['key']
json_object = s3_client.get_object(Bucket=bucket,Key=json_file_name)
jsonFileReader = json_object['Body'].read()
jsonDict = json.loads(jsonFileReader)
table = dynamodb.Table('Items')
with table.batch_writer() as batch:
for product in jsonDict["Products"]:
batch.put_item(Item=product)
logger.info(product)
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}