DynamoDB Scan返回结果不符合预期,如何提取纯ARN字符串?
The reason you're getting that structured output is because you're using the boto3 client interface, which returns raw DynamoDB data types (like {'S': 'string'} for string values). To get just the ARN strings, you need to parse each item in the scan response.
Here's how to modify your code to get the desired output:
Basic Version (for small tables)
import boto3 dynamo = boto3.client('dynamodb') def get_arns(): response = dynamo.scan(TableName='AllAccountARNs') # Extract ARNs from each item arns = [item['ARNs']['S'] for item in response['Items']] # Print each ARN on a new line for arn in arns: print(arn) get_arns()
This will output exactly what you want:
arn:aws:iam::xxxxxxx:role/custom_role arn:aws:iam::yyyyyyy:role/custom_role arn:aws:iam::zzzzzzz:role/custom_role
Handling Large Tables (Pagination)
If your DynamoDB table has more than 1MB of data (the default scan limit), the initial scan call won't return all items. You'll need to handle pagination using the LastEvaluatedKey or use a paginator:
import boto3 dynamo = boto3.client('dynamodb') def get_arns(): paginator = dynamo.get_paginator('scan') # Iterate through all pages of results for page in paginator.paginate(TableName='AllAccountARNs'): arns = [item['ARNs']['S'] for item in page['Items']] for arn in arns: print(arn) get_arns()
Alternative: Use boto3 Resource for Simpler Parsing
If you switch to the boto3 resource interface, it automatically deserializes the DynamoDB data types into native Python types, which can make your code cleaner:
import boto3 dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('AllAccountARNs') def get_arns(): response = table.scan() arns = [item['ARNs'] for item in response['Items']] for arn in arns: print(arn) get_arns()
This resource approach eliminates the need to access the ['S'] key directly, since it converts the DynamoDB string type to a regular Python string.
内容的提问来源于stack exchange,提问作者dmn0972

