在python 3中,我有像这样的JSON字符串
{
"tag" : "مو",
"id" : 1
}
我使用json.loads
方法,但它没有转换 如何将其转换为 Unicode 字符串并使用它。
您可以使用正则表达式来匹配 HTML 实体并将其替换为其 Unicode 字符:
import json
import re
raw_data = '''
{
"tag" : "مو",
"id" : 1
}
'''
data = json.loads(raw_data)
data['tag'] = re.sub(r'&#(d+);',lambda m: chr(int(m.group(1))),data['tag'])
print(data)
输出:
{'tag': 'مو', 'id': 1}
如果可能的话,更好的解决方案是首先正确编写 JSON,这将是以下任一:
option1 = json.dumps(data)
option2 = json.dumps(data, ensure_ascii=False)
print(option1)
print(option2)
输出:
{"tag": "u0645u0648", "id": 1}
{"tag": "مو", "id": 1}