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

如何从AWS目标组JSON文件提取TargetGroupArn到Python列表?

解决AWS目标组ARN提取问题

Hey, let's break down why your current code isn't returning any ARNs. The issue is with how you're traversing the JSON structure:

Your original code loops through the top-level keys of the entire data dictionary, but TargetGroupArn isn't a top-level key—it lives inside each dictionary in the TargetGroups list that you've already assigned to items (though you don't use that variable later).

Here's the fixed code

First, let's go with a clear, readable version:

import json

with open('target_groups.json') as f:
    data = json.load(f)

# Grab the list of target groups from the JSON
target_groups = data['TargetGroups']
arn_list = []

# Loop through each target group entry to extract the ARN
for group in target_groups:
    # Use .get() to avoid KeyError if a group unexpectedly lacks the ARN field
    arn = group.get('TargetGroupArn')
    if arn:
        arn_list.append(arn)

print(arn_list)

If you prefer a more concise approach, a list comprehension works great here (assuming every target group definitely has a TargetGroupArn):

import json

with open('target_groups.json') as f:
    data = json.load(f)

arn_list = [group['TargetGroupArn'] for group in data['TargetGroups']]
print(arn_list)

Why your original code failed

Your loop for key, val in data.items() checks the top-level keys of the JSON (which is just 'TargetGroups' in this case). You never actually look inside the list of target groups, so it never finds the 'TargetGroupArn' keys that are nested deeper. That's why your arn_list stayed empty!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:52:01