2
import boto3
client = boto3.client('secretsmanager')

response = client.get_secret_value(SecretId='xxxx')
print('entire response:', response)
print('SecretString:',response['SecretString'])
print('testvalue:'response['SecretString']["testkey"])    

我正在尝试实现 aws secretsmanager 并需要访问测试值。

entire response:{---, u'SecretString': u'{"testkey":"testvalue","testkey2":"testvalue2"}', ----}
Secretstring:{"testkey":"testvalue","testkey2":"testvalue2"}
Traceback (most recent call last):
  File "secretmanagertest.py", line 7, in <module>
    print('testvalue',response['SecretString']["testkey"])
TypeError: string indices must be integers

当我尝试使用整数时,我只会得到特定的字符。

print(response['SecretString'][0])
{
print(response['SecretString'][1])
"
print(response['SecretString'][2])
t

等等

4

1 回答 1

3

响应是嵌套的 JSON 文档,而不是字典。首先对其进行解码,使用json.loads()

import json

secret = json.loads(response['SecretString'])
print(secret['testkey'])

演示:

>>> import json
>>> response = {u'SecretString': u'{"testkey":"testvalue","testkey2":"testvalue2"}'}
>>> response['SecretString']
u'{"testkey":"testvalue","testkey2":"testvalue2"}'
>>> json.loads(response['SecretString'])
{u'testkey2': u'testvalue2', u'testkey': u'testvalue'}
>>> json.loads(response['SecretString'])['testkey']
u'testvalue'
于 2018-06-14T11:12:03.583 回答