【发布时间】:2014-09-27 03:28:20
【问题描述】:
我有一本字典 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 中的字节 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 中的字节 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()
【问题讨论】:
-
data字典中的字符串实际上不是 UTF-8 编码的;将其解码为 Unicode 失败。 -
您能否将实际的
data字典放入您的帖子中?只需包含print data的输出即可。 -
data变量太大,无法粘贴。无论如何,我认为我的字典中只有一个条目导致了这个问题。我编辑了我的帖子。 -
该字符串确实是不是 UTF-8 编码的。那应该是inverted question mark 吧?
-
您必须将该值替换为实际的 UTF-8 编码值,或者将其替换为 Unicode 值(因此在将其传递给
json.dump()之前先明确解码)。跨度>
标签: python json unicode encoding utf-8