lan*_*iac 2 byte json python-2.7
我有
import json
a = {'code': 'exam', 'list': [{'note': '2', 'right': '2', 'question': 'Tr\xe0n V?n H\xf9ng', 'answers': ['etreetetetetret', 'reteretet', 'tedtetetet', 'etetetet']}], 'id': 1, 'level': 1}
json.dumps(a)
Run Code Online (Sandbox Code Playgroud)
===>错误:UnicodeDecodeError:'utf8'编解码器无法解码位置2的字节0xe0:无效
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/json/__init__.py", line 250, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "/usr/lib/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xe0 in position 2: invalid continuation byte
Run Code Online (Sandbox Code Playgroud)
创建JSON输出时,首先将所有字节字符串(在Python 2中,不是 Unicode字符串的任何字符串都是字节字符串)解码为Unicode。json.dumps()缺省情况下,该方法使用UTF-8。您的输入数据未使用UTF-8。
告诉json.dumps()您要使用哪种编码,或者解码您的字符串以对自己进行编码。在这里,您似乎正在使用Latin-1字符串,因此请使用:
json.dumps(a, encoding='latin1')
Run Code Online (Sandbox Code Playgroud)
演示:
>>> import json
>>> a = {'code': 'exam', 'list': [{'note': '2', 'right': '2', 'question': 'Tr\xe0n V?n H\xf9ng', 'answers': ['etreetetetetret', 'reteretet', 'tedtetetet', 'etetetet']}], 'id': 1, 'level': 1}
>>> json.dumps(a, encoding='latin1')
'{"code": "exam", "list": [{"note": "2", "right": "2", "question": "Tr\\u00e0n V?n H\\u00f9ng", "answers": ["etreetetetetret", "reteretet", "tedtetetet", "etetetet"]}], "id": 1, "level": 1}'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8568 次 |
| 最近记录: |