【发布时间】:2018-09-17 22:38:56
【问题描述】:
我有一个 python 脚本,它可以提取我拥有的所有 AWS 账户中的所有 EC2 实例 ID 和标签。我试图只解析一个键的一个值。具体来说,我只想从响应中解析Key email 的Value,但我收到错误消息:list indices must be integers or slices, not str。下面是我的代码和json 响应。
Code:
import boto3
import json
conn = boto3.resource('ec2',
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
aws_session_token=session_token)
instances = conn.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
for instance in instances:
host_list = instance.id
host_tags = instance.tags
print(host_tags['Key']['email']['Value'])
Sample JSON:
[{
'Key': 'gitlab',
'Value': 'true'
}, {
'Key': 'portfolio',
'Value': 'xxx'
}, {
'Key': 'runner-manager-name',
'Value': 'xxxxxx'
}, ...
]
Error:
list indices must be integers or slices, not str
【问题讨论】:
-
尝试:email = [tag['Value'] for tag in host_tags if tag['Key'] == 'email'][0]
-
既然它在抱怨
host_tags[][][],打印出host_tags看看它是什么格式。如果是,我怀疑是[{'Key': 'gitlab', 'Value': 'true'}, ...,那么host_tags['Key']是没有意义的。 -
因为你的 json 结构看起来像这样
[ { }, ...]。这表明数据以列表开头,即[ ](因此它期望数字索引),那么只有里面的值是一个字典,这里使用你的字典键索引。
标签: json amazon-web-services amazon-ec2 python-3.6 boto3