首先注意符号 β(希腊语 beta)在 UTF-8 中具有十六进制表示:CE B2
我有使用 json 字符串的 Python 2.7 旧源代码:
u'{"something":"text \\u00ce\\u00b2 text..."}'
然后我调用 json.loads(string) 或 json.loads(string, 'utf-8'),但结果是带有 UTF-8 字符的 Unicode 字符串:
u'text \xce\xb2 text'
我想要的是普通的Python Unicode(UTF-16?)字符串:
u'text β text'
如果我打电话:
text = text.decode('unicode_escape')
在 json.loads 之前,我得到了正确的 Unicode β 符号,但它也通过替换所有新行来破坏 json - \n
问题是,如何只转换"\\u00ce\\00b2"
部分而不影响其他json特殊字符?
(我是 Python 新手,这不是我的源代码,所以我不知道它是如何工作的。我怀疑该代码只适用于 ASCII 字符)
最佳答案
也许是这样的。这仅限于 2 字节 UTF-8 字符。
import re
j = u'{"something":"text \\u00ce\\u00b2 text..."}'
def decodeu (match):
u = '%c%c' % (int(match.group(1), 16), int(match.group(2), 16))
return repr(u.decode('utf-8'))[2:8]
j = re.sub(r'\\u00([cd][0-9a-f])\\u00([89ab][0-9a-f])',decodeu, j)
print(j)
返回示例的 {"something":"text\u03b2 text..."}
。此时,您可以将其作为常规 JSON 导入并获得您想要的最终字符串。
result = json.loads(j)
关于python - JSON 包含不正确的 UTF-8\u00ce\u00b2 而不是 Unicode\u03b2,如何在 Python 中修复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47671985/