python3 utf8字符串是否保存为utf8?

2024-10-06 18:32:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道哪个头衔适合我的情况。你知道吗

data=[]

for title in titles:
     real_title = ''.join(str(title.text).split())
     print(real_title)
     data.append(real_title)

with open(os.path.join(BASE_DIR, 'result.json'), 'w+') as json_file:
    json.dump(data, json_file)

当python~~.py时,效果非常好。打印(真实标题)节目

이스케이프룸

但当我打开json文件时:

"\uc774\uc2a4\ucf00\uc774\ud504\ub8f8"

有什么问题吗?为什么utf-8字母按字面意思保存到utf-8?你知道吗


Tags: textinjsonfordatatitle情况real
1条回答
网友
1楼 · 发布于 2024-10-06 18:32:47

您看到的是Unicode转义码;例如,"\uc774"是带有Unicode码位C774 16位十六进制的字符。默认情况下,对于任何不在ASCII范围(0到127十进制)内的字符,都会发生此转义。你知道吗

您可以将ensure_ascii参数设置为False

If ensure_ascii is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is false, these characters will be output as-is.

示例:

>>> import json
>>> data = {"key": "이스케이프룸"}
>>> json.dumps(data)
'{"key": "\\uc774\\uc2a4\\ucf00\\uc774\\ud504\\ub8f8"}'
>>> json.dumps(data, ensure_ascii=False)
'{"key": "이스케이프룸"}'

相关问题 更多 >