我有一本字典data
,存放在这里:
key
- IDvalue
-这个事件的名称,其中value
是一个UTF-8字符串。现在,我想把这张地图写成一个json文件。我试过用这个:
with open('events_map.json', 'w') as out_file:
json.dump(data, out_file, indent = 4)
但这给了我一个错误:
UnicodeDecodeError:'utf8‘编解码器无法解码0位置的字节0 0xbf :无效的开始字节
现在,我还试着:
with io.open('events_map.json', 'w', encoding='utf-8') as out_file:
out_file.write(unicode(json.dumps(data, encoding="utf-8")))
但这也会引发同样的错误:
UnicodeDecodeError:'utf8‘编解码器无法解码0位置的字节0 0xbf :无效的开始字节
我也尝试过:
with io.open('events_map.json', 'w', encoding='utf-8') as out_file:
out_file.write(unicode(json.dumps(data, encoding="utf-8", ensure_ascii=False)))
但这会引发错误:
UnicodeDecodeError:'ascii‘编解码器不能解码位置3114的字节0xbf :序数不在范围(128个)
关于如何解决这个问题,有什么建议吗?
编辑:--我相信这是引起我问题的那一行:
> data['142']
'\xbf/ANCT25'
编辑2:从文件中读取data
变量。因此,在从文件中读取它之后:
data_file_lines = io.open(file_name, 'r', encoding='utf8').readlines()
然后我会:
with io.open('data/events_map.json', 'w', encoding='utf8') as json_file:
json.dump(data, json_file, ensure_ascii=False)
这给了我一个错误:
TypeError:必须是unicode,而不是str
然后,我尝试使用数据字典来实现这一点:
for tuple in sorted_tuples (the `data` variable is initialized by a tuple):
data[str(tuple[1])] = json.dumps(tuple[0], ensure_ascii=False, encoding='utf8')
其次是:
with io.open('data/events_map.json', 'w', encoding='utf8') as json_file:
json.dump(data, json_file, ensure_ascii=False)
但是,同样的错误:
TypeError: must be unicode, not str
当我使用简单的open
函数从文件中读取时,也会出现同样的错误:
data_file_lines = open(file_name, "r").readlines()
发布于 2014-08-04 16:00:04
异常是由data
字典的内容引起的,其中至少有一个键或值不是UTF-8编码的。
您必须替换该值;要么替换一个编码为UTF-8的值,要么将其解码为unicode
对象,只使用该值的任何编码对该值进行正确的编码:
data['142'] = data['142'].decode('latin-1')
将该字符串解码为拉丁文1编码的值。
https://stackoverflow.com/questions/25122371
复制相似问题