[英]Python | How to parse JSON from results from AWS response?
我試圖獲得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()
這是我在調用print(response)
時從AWS獲得的print(response)
。
{
'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'
}
}
}
非常感謝!
根據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']
編輯:請注意,上面從可能的多個實例中獲取第一個實例的VersionLabel。 如果您有多個實例且它們恰好具有不同的VersionLabel值,那么您需要額外的邏輯來獲得所需的實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.