Reputation: 179
I have the code as below,
with open(Elastic_Secret_File) as f:
yaml_data = yaml.safe_load(f)
for key, value in dict(yaml_data["xxx"]["xxxx"]["xxxx"]["xxxx"]["xxxxx"]).items():
Ela_User = value["clusterCredentials"]["username"]
Ela_Pass = str(value["clusterCredentials"]["password"].replace("'", ""))
#Ela_Pass = value["clusterCredentials"]["password"]
Ela_Host = value["urls"]
print (Ela_Pass)
es_secret_data = toml.load("./secrets/elasticsearch-password.toml")
es_secret_data['password'] = Ela_Pass
es_secret_data1 = ast.literal_eval(json.dumps(es_secret_data))
print (es_secret_data1)
with open('./secrets/elasticsearch-password.toml', 'w') as f:
elastic_toml_string = toml.dump(es_secret_data1, f)
The Ela_Pass contains the password string with \ characters. The json adds extra backslash to the string which is not good as I want the final string without extra backslash.
for e.g
Ela_Pass = 1\n2\t3\a6
{'password': '1\n2\t3\\a6'}
I've tried to use .decode('string-escape) and .decode('unicode-escape') , but it works only for special sequences supported by Python.
Please help, how do I maintain my original string without any additional backslash ?
Upvotes: 1
Views: 5315
Reputation: 2439
You could remove dublicated backslashes with:
json.dumps(es_secret_data).replace('\\\\', '\\')
you need to escape the backslash character in python with a backslash. Thats why there is a quadruple-backslash.
But keep in mind that json adds those extra-backslashes for a reason. After replacing them, you will not be able to use json.reads()
to get the original password. Json uses the backslash to escape the backslash. So a double-backslash in json
stands for a single json-charakter
Upvotes: 3