python 3 - 如何清理带有双反斜杠和 u00 的 json 字符串

python 3 - how to clean json string with double backslashes and u00

我有几个丑陋的 json 字符串,如下所示:

test_string = '{\"test_key\": \"Testing tilde \u00E1\u00F3\u00ED\"}'

我需要将其转换为视觉上更友好的字典,然后将其保存到文件中:

{'test_key': 'Testing tilde áóí'}

为此我正在做:

test_string = test_string.replace("\\"", "\"") #  I suposse there is a safer way to do this
print(test_string)
#{"test_key": "Testing tilde \u00E1\u00F3\u00ED"}

test_dict = json.loads(test_string, strict=False)
print(test_dict)
#{'test_key': 'Testing tilde áóí'}

此时test_dict似乎是正确的。然后我将它保存到一个文件中:

with open('test.json', "w") as json_w_file:
    json.dump(test_dict, json_w_file)

此时test.json的内容就是json的丑化版本:

{"test_key": "Testing tilde \u00E1\u00F3\u00ED"}

有没有更安全的方法将我丑陋的 json 转换为字典? 那么我怎样才能将我的词典的视觉友好版本保存到文件中呢?

Python 3

对我来说,字符串看起来像双重编码 json。这对其进行解码并写入一个 utf-8 json 文件。

test_string = '{\"test_key\": \"Testing tilde \u00E1\u00F3\u00ED\"}'

test_dict = json.loads(json.loads(f'"{test_string}"'))

with open('test.json', "w") as json_w_file:
    json.dump(test_dict, json_w_file, ensure_ascii=False)