sed*_*rep 4 python json boto amazon-web-services
我正试图获得的价值VersionLabel是php-v1,但我的代码不能正常工作,我不知道我做错了什么.
你能不能让我知道什么是错的,我怎么解析php-v1?
这是我的错误消息.
TypeError: the JSON object must be str, not 'dict'
这是我的代码.
#!/usr/bin/env python3
import boto3
import json
def get_label():
try:
env_name = 'my-env'
eb = boto3.client('elasticbeanstalk')
response = eb.describe_instances_health(
EnvironmentName=env_name,
AttributeNames=[
'Deployment'
]
)
#print(response)
data = json.loads(response)
print(data['VersionLabel'])
except:
raise
if __name__ == '__main__':
get_label()
Run Code Online (Sandbox Code Playgroud)
这是我在print(response)调用AWS时得到的响应.
{
'InstanceHealthList':[
{
'InstanceId':'i-12345678',
'Deployment':{
'DeploymentId':2,
'DeploymentTime':datetime.datetime(2016,
9,
29,
4,
29,
26,
tzinfo=tzutc()),
'Status':'Deployed',
'VersionLabel':'php-v1'
}
}
],
'ResponseMetadata':{
'HTTPStatusCode':200,
'RequestId':'12345678-1234-1234-1234-123456789012',
'RetryAttempts':0,
'HTTPHeaders':{
'content-length':'665',
'content-type':'text/xml',
'date':'Sat, 01 Oct 2016 11:04:56 GMT',
'x-amzn-requestid':'12345678-1234-1234-1234-123456789012'
}
}
}
Run Code Online (Sandbox Code Playgroud)
非常感谢!
小智 8
根据boto3文档[ http://boto3.readthedocs.io/en/latest/reference/services/elasticbeanstalk.html?highlight=describe_instances_health#ElasticBeanstalk.Client.describe_instances_health],describe_instances_health方法返回dict而不是json.因此,您无需进行转换.要从数据中获取VersionLabel,请使用 -
data ['InstanceHealthList'][0]['Deployment']['VersionLabel']
Run Code Online (Sandbox Code Playgroud)
编辑:请注意,上面从可能的多个实例中获取第一个实例的VersionLabel.如果您有多个实例且它们恰好具有不同的VersionLabel值,那么您需要额外的逻辑来获得所需的实例.
以防万一要求将 boto 响应转换为合法的 json 格式 -
import json
response_json = json.dumps(response, default=str))
Run Code Online (Sandbox Code Playgroud)
datetime.datetime 需要在 dict 到 json 转换过程中处理