我正在使用Boto3从小型dynamoDB表中检索并返回所有数据。我的目标是从输出中删除attributeTypes。
以下是我的输出:
{"Items": [{"PresidentialCandidate_ID": {"S": "Trump"}, "Vote": {"N": "47"}}, {"PresidentialCandidate_ID": {"S": "Stein"}, "Vote": {"N": "16"}}, {"PresidentialCandidate_ID": {"S": "Dwayne"}, "Vote": {"N": "1"}}, {"PresidentialCandidate_ID": {"S": "none"}, "Vote": {"N": "11"}}, {"PresidentialCandidate_ID": {"S": "Johnson"}, "Vote": {"N": "13"}}, {"PresidentialCandidate_ID": {"S": "Clinton"}, "Vote": {"N": "22"}}], "Count": 6, "ScannedCount": 6}
我想要的输出:
{"Items":[{"PresidentialCandidate_ID":"Trump","Vote":47},{"PresidentialCandidate_ID":"Stein","Vote":16},{"PresidentialCandidate_ID":"Dwayne","Vote":1},{"PresidentialCandidate_ID":"none","Vote":11},{"PresidentialCandidate_ID":"Johnson","Vote":13},{"PresidentialCandidate_ID":"Clinton","Vote":22}],"Count":6,"ScannedCount":6}
我尝试了以下操作:
import boto3
import json
dynamodb = boto3.client('dynamodb')
def lambda_handler(event, context):
table = dynamodb.scan(TableName="PresidentialCandidate", ConsistentRead=True)
del table['ResponseMetadata']
table = json.dumps(table)
print(table)
return {
}
关于如何过滤出attributeType以获取所需输出的任何建议?
您只能尝试使用此代码以所需的方式返回数据。
import boto3
import json
dynamodb = boto3.client('dynamodb')
def lambda_handler(event, context):
table = dynamodb.scan(TableName="PresidentialCandidate", ConsistentRead=True)
items = table['Items']
idx = 0
for item in items:
for key in item:
value = list(item[key].values())[0]
items[idx][key] = value
idx += 1
return items
您还可以将所需的新格式对象一次存储到表中。这样,attributeTypes将不再反映出来,并且没有attributeTypes也可以得到结果。您可以尝试以下代码:)
import boto3
import json
dynamodb = boto3.client('dynamodb')
def lambda_handler(event, context):
table = dynamodb.scan(TableName="PresidentialCandidate", ConsistentRead=True)
items = table['Items']
idx = 0
for item in items:
for key in item:
value = list(item[key].values())[0]
# added this line to write and replace the by the new formatted object
dynamodb.put_item(TableName="PresidentialCandidate", Item=item)
items[idx][key] = value
idx += 1
return items