use*_*096 0 boto amazon-web-services amazon-dynamodb boto3 aws-lambda
我正在使用 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}
Run Code Online (Sandbox Code Playgroud)
我想要的输出:
{"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}
Run Code Online (Sandbox Code Playgroud)
我尝试了以下方法:
{"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}
Run Code Online (Sandbox Code Playgroud)
关于如何过滤掉 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
Run Code Online (Sandbox Code Playgroud)
您还可以将新的所需格式化对象一次性存储到表中。这样,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 old format by the new formatted object
dynamodb.put_item(TableName="PresidentialCandidate", Item=item)
items[idx][key] = value
idx += 1
return items
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1816 次 |
| 最近记录: |