python - JSON 包含不正确的 UTF-8\u00ce\u00b2 而不是 Unicode\u03b2,如何在 Python 中修复?

标签 python json string unicode utf-8

首先注意符号 β(希腊语 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/

相关文章:

c# - 复杂对象的JSON解析

python - 如何将列表中的值输入到字符串中?

python - Pandas 数据框 : return column that is a compression of other columns

python - 如何同时运行2个不同的进程?

java - 由于循环依赖,在基类以外的对象上指定 Jackson JSON 子类型

json - Sproutcore和JSON数据

java - java "stringtokenizer.nextToken(delimiter); "是如何工作的?

python - 最好的方法是计算 python 中列表和字符串之间的匹配次数

python - matplotlib:颜色条及其文本标签

javascript - Python中是否有相当于Javascript的hasOwnProperty()?