0

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 sting 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 sequeunces supported by Pyton.

Please help, how do i mantain my original string without any additional backslash ?

4

1 回答 1

0

您可以使用以下方法删除重复的反斜杠:

json.dumps(es_secret_data).replace('\\\\', '\\')

你需要用反斜杠转义python中的反斜杠字符。这就是为什么有一个四反斜杠。

但请记住,json 添加这些额外的反斜杠是有原因的。更换它们后,您将无法使用json.reads()获取原始密码。Json 使用反斜杠来转义反斜杠。所以双反斜杠json代表单个 json-charakter

于 2020-12-28T13:15:20.000 回答