Python解析JSON文件:处理大JSON中的UserDetailList段
Parsing the
UserDetailList JSON Snippet with Python Got it, let's break down how to parse that AWS IAM user JSON snippet using Python. We'll use Python's built-in json module—no extra packages needed, which makes this straightforward.
First, let's make sure your JSON snippet is valid (I've cleaned up the trailing ellipsis to complete the Arn value):
import json # Validated JSON data based on your snippet json_input = ''' { "UserDetailList": [ { "UserName": "citrix-xendesktop-ec2-provisioning", "GroupList": [], "CreateDate": "2017-11-07T14:20:14Z", "UserId": "AIDAI2YJINPRUEM3XHKXO", "Path": "/", "AttachedManagedPolicies": [ { "PolicyName": "AmazonEC2FullAccess", "PolicyArn": "arn:aws:iam::aws:policy/AmazonEC2FullAccess" }, { "PolicyName": "AmazonS3FullAccess", "PolicyArn": "arn:aws:iam::aws:policy/AmazonS3FullAccess" } ], "Arn": "arn:aws:iam::279052847476:user/citrix-xendesktop-ec2-provisioning" } ] } ''' # Parse JSON string into a Python dictionary parsed_json = json.loads(json_input) # Access the UserDetailList array user_list = parsed_json["UserDetailList"] # Process each user entry for user in user_list: # Extract core user attributes print(f"User: {user['UserName']}") print(f"User ID: {user['UserId']}") print(f"Created: {user['CreateDate']}") print(f"ARN: {user['Arn']}") # List attached managed policies print("Attached Policies:") for policy in user["AttachedManagedPolicies"]: print(f" • {policy['PolicyName']} ({policy['PolicyArn']})") print("\n---\n")
Key Notes:
- Loading JSON from a File: If your data is stored in a file instead of a string, swap
json.loads()forjson.load(). Example:with open('iam_users.json', 'r') as file: parsed_json = json.load(file) - Preserving Technical Terms: All IAM-specific fields like
UserId,Arn, andPolicyArnare retained exactly as in your original snippet—no modifications here. - Extending the Logic: You can add filters or transformations easily. For example, to fetch only users with
AmazonS3FullAccessattached:s3_users = [ user for user in user_list if any(p['PolicyName'] == 'AmazonS3FullAccess' for p in user['AttachedManagedPolicies']) ]
内容的提问来源于stack exchange,提问作者Milister
相关产品推荐
相关产品推荐

