You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DynamoDB Scan返回结果不符合预期,如何提取纯ARN字符串?

Solution

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:58:34