Python序列化错误
当我的python代码尝试将dictionary对象转换为Json字符串时,它引发了以下异常:Python序列化错误,python,json,Python,Json,当我的python代码尝试将dictionary对象转换为Json字符串时,它引发了以下异常: SerializationError: ({'status': 'rd', 'name': 'Detecci\xf3nInt/.unclassified.ez', 'st': 0}, UnicodeDecodeError('utf8', 'Detecci\xf3nInt/.unclassified.ez', 7, 8, 'invalid continuation byte')) 请给出解决此问
SerializationError: ({'status': 'rd',
'name': 'Detecci\xf3nInt/.unclassified.ez', 'st': 0},
UnicodeDecodeError('utf8', 'Detecci\xf3nInt/.unclassified.ez', 7, 8,
'invalid continuation byte'))
请给出解决此问题的提示。默认情况下json.dump()
使用UTF8编码,但是,词典中名称
键的值不是UTF8。它看起来像是ISO-8859-X编码之一。您可以使用encoding
参数指定编码:
import json
d = {'status': 'rd', 'name': 'Detecci\xf3nInt/.unclassified.ez', 'st': 0}
s = json.dumps(d, encoding='ISO-8859-1')
print(s)
输出
{"status": "rd", "name": "Detecci\u00f3nInt/.unclassified.ez", "st": 0}
{“status”:“rd”,“name”:“Detecci\u00f3nInt/.unclassified.ez”,“st”:0}
关于使用哪种编码,我有点猜测,因此您可能想检查哪种编码是数据的正确编码。您正在运行的python版本是什么?python版本是2.6.6您是否有可能运行python 3,因为这样它可能会自动解决您的问题。我想UTF-8比ISO8859-1更宽,为什么ISO8859-1可以支持,但UTF-8不支持?它们的编码不同
u'\xf3'
是带有锐音符的拉丁文小写字母O的unicode码点。当编码为ISO-8859-1时,这是字节'\xf3'
,但当编码为UTF-8时,这是字节序列'\xc3\xb3'
。您可能需要签出。