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

如何遍历boto3嵌套JSON字典获取VpcEndpointId值

如何遍历嵌套JSON结构获取所有VpcEndpointId的值

你需要处理的JSON结构如下:

response = {
    "VpcEndpoints": [
        {
            "VpcEndpointId": "vpce-123",
            "VpcEndpointType": "GatewayLoadBalancer",
            "VpcId": "vpc-test",
            "ServiceName": "com.amazonaws.com",
            "State": "available",
            "SubnetIds": [
                "subnet-random"
            ],
            "IpAddressType": "ipv4",
            "RequesterManaged": True,
            "NetworkInterfaceIds": [
                "eni-123"
            ],
            "CreationTimestamp": "2022-10-28T01:23:23.924Z",
            "Tags": [
                {
                    "Key": "AWSNetworkFirewallManaged",
                    "Value": "true"
                },
                {
                    "Key": "Firewall",
                    "Value": "arn:aws:network-firewall:us-west-2"
                }
            ],
            "OwnerId": "123"
        },
        {
            "VpcEndpointId": "vpce-456",
            "VpcEndpointType": "GatewayLoadBalancer",
            "VpcId": "vpc-<value>",
            "ServiceName": "com.amazonaws.vpce.us-west-2",
            "State": "available",
            "SubnetIds": [
                "subnet-<number>"
            ],
            "IpAddressType": "ipv4",
            "RequesterManaged": True,
            "NetworkInterfaceIds": [
                "eni-<value>"
            ],
            "CreationTimestamp": "2022-10-28T01:23:42.113Z",
            "Tags": [
                {
                    "Key": "AWSNetworkFirewallManaged",
                    "Value": "True"
                },
                {
                    "Key": "Firewall",
                    "Value": "arn:aws:network-firewall:%l"
                }
            ],
            "OwnerId": "random"
        }
    ]
}

你的错误尝试代码:

for endpoint in response['VpcEndpoints']:
#for vpc_endpoint in endpoint['VpcEndpointId']:
for vpc_endpoint in endpoint:
    if vpc_endpoint == 'VpcEndpointId':
        type(vpc_endpoint)

问题分析

你当前的代码仅遍历了字典的键,判断键名是否为VpcEndpointId,但未获取该键对应的值。实际上无需遍历所有字典键,直接通过键名即可取值。

解决方案

方式1:直接打印每个VpcEndpointId的值

for endpoint in response['VpcEndpoints']:
    # 直接通过键名获取对应的值
    print(endpoint['VpcEndpointId'])

方式2:收集所有值到列表中

如果需要将所有VpcEndpointId的值存储起来后续使用,可使用列表推导式,简洁高效:

vpc_endpoint_ids = [endpoint['VpcEndpointId'] for endpoint in response['VpcEndpoints']]
print(vpc_endpoint_ids)
# 输出: ['vpce-123', 'vpce-456']

方式3:处理可能不存在键的情况(可选)

若担心部分端点没有VpcEndpointId键,可使用get方法避免报错:

vpc_endpoint_ids = []
for endpoint in response['VpcEndpoints']:
    # get方法若键不存在会返回None,也可指定默认值
    endpoint_id = endpoint.get('VpcEndpointId', 'N/A')
    vpc_endpoint_ids.append(endpoint_id)

内容的提问来源于stack exchange,提问作者Lam2020

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 02:35:35