我有幾個丑陋的 json 字串,如下所示:
test_string = '{\\"test_key\\": \\"Testing tilde \\u00E1\\u00F3\\u00ED\\"}'
我需要將其轉換為視覺上更友好的字典,然后將其保存到檔案中:
{'test_key': '測驗波浪號 áóí'}
所以為此我正在做:
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": "測驗波浪號 \u00E1\u00F3\u00ED"}
有沒有更安全的方法將我丑陋的 json 轉換為字典?那么我怎樣才能將我的字典的視覺友好版本保存到檔案中呢?
蟒蛇 3
uj5u.com熱心網友回復:
字串對我來說看起來像雙重編碼的 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/370900.html
