如何从AWS目标组JSON文件提取TargetGroupArn到Python列表?
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

