change198
change198

Reputation: 2065

Fetch unicode string key/value using python

I have a unicode string called

get_secret_value_response =  {u'Name':....u'SecretString':u'{"username": "username", "password": "password"}'

I would like to fetch the username and password. however, when I tried accessing using as dict for python it's saying

if 'SecretString' in get_secret_value_response:
        secret = get_secret_value_response["SecretString"]
    print(secret.keys())
    'unicode' object has no attribute 'keys'

Upvotes: 0

Views: 129

Answers (2)

mursalin
mursalin

Reputation: 1181

your get_secret_value_response["SecretString"] returns a str. You have to convert it to a json/dict.

import json

if 'SecretString' in get_secret_value_response:
    secret = json.loads(get_secret_value_response["SecretString"])
    print(secret.keys())

Upvotes: 1

Leo Arad
Leo Arad

Reputation: 4472

The error is causing by 'SecretString' is a string and it's treated as a dictionary.
To convert it to a dictionary you can use literal_eval method like

from ast import literal_eval

get_secret_value_response = {u'SecretString':u'{"username": "username", "password": "password"}'}
if 'SecretString' in get_secret_value_response:
    secret = literal_eval(get_secret_value_response["SecretString"])

print(secret.keys())

This will output

dict_keys(['username', 'password'])

The most important thing here that the secret variable will be converted to a dictionary and you will be able to use it by keys values pairs.

Upvotes: 0

Related Questions