Python |如何从 AWS 响应结果中解析 JSON?

问题描述 投票:0回答:2

我试图获取

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 获得的响应。

{
   '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'
      }
   }
}

非常感谢!

python json amazon-web-services boto
2个回答
11
投票

根据 boto3 文档

describe_instances_health
方法返回 dict 而不是 json。因此,您无需进行转换。

要从数据中获取 VersionLabel,请使用:

data ['InstanceHealthList'][0]['Deployment']['VersionLabel']

编辑:请注意,上面的代码从可能的多个实例中获取了第一个实例的

VersionLabel
。如果您有多个实例,并且它们碰巧具有不同的
VersionLabel
值,那么您将需要额外的逻辑来获取您需要的实例。


5
投票

以防万一要求将 boto 响应转换为合法的 json 格式 -

import json
response_json = json.dumps(response, default=str))

datetime.datetime需要在dict到json转换过程中处理

© www.soinside.com 2019 - 2024. All rights reserved.