无法访问 dict in dict with string indices must be integer 错误

Fail to acces dict in dict with string indeces must be integer error

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

等等

响应是嵌套的 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'