json.dump - UnicodeDecodeError:'utf8'编解码器无法解码位置0的字节0xbf:无效的起始字节

Bel*_*gor 11 python unicode encoding json utf-8

我有一个data我存储的字典:

  • key - 活动的ID

  • value- 此事件的名称,其中value是UTF-8字符串

现在,我想将此地图写入json文件.我试过这个:

with open('events_map.json', 'w') as out_file:
    json.dump(data, out_file, indent = 4)
Run Code Online (Sandbox Code Playgroud)

但这给了我错误:

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")))
Run Code Online (Sandbox Code Playgroud)

但这会引发同样的错误:

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)))
Run Code Online (Sandbox Code Playgroud)

但这会引发错误:

UnicodeDecodeError:'ascii'编解码器无法解码位置3114中的字节0xbf:序数不在范围内(128)

关于如何解决这个问题的任何建议?

编辑: 我相信这是导致我这个问题的路线:

> data['142']
'\xbf/ANCT25'
Run Code Online (Sandbox Code Playgroud)

编辑2: 该data变量被从文件中读取.所以,从文件中读取后:

data_file_lines = io.open(file_name, 'r', encoding='utf8').readlines()
Run Code Online (Sandbox Code Playgroud)

然后我做:

with io.open('data/events_map.json', 'w', encoding='utf8') as json_file:
        json.dump(data, json_file, ensure_ascii=False)
Run Code Online (Sandbox Code Playgroud)

这给了我错误:

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')
Run Code Online (Sandbox Code Playgroud)

再次,接着是:

with io.open('data/events_map.json', 'w', encoding='utf8') as json_file:
    json.dump(data, json_file, ensure_ascii=False)
Run Code Online (Sandbox Code Playgroud)

但同样的错误:

TypeError: must be unicode, not str
Run Code Online (Sandbox Code Playgroud)

当我使用简单open函数从文件中读取时,我得到了同样的错误:

data_file_lines = open(file_name, "r").readlines()
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 15

异常是由data字典的内容引起的,至少有一个键或值不是 UTF-8编码的.

你必须替换这个值; 或者通过用一个值,该值是 UTF-8编码的,或者通过将其进行解码,以一个unicode由解码只是与任何编码是该值的正确的编码值对象:

data['142'] = data['142'].decode('latin-1')
Run Code Online (Sandbox Code Playgroud)

将该字符串解码为Latin-1编码的值.

  • 没关系,我终于解决了!我从这里得到了答案:http://stackoverflow.com/questions/12309269/write-json-data-to-file-in-python/14870531#14870531(Python 2.x 的代码)。无论如何,@Martijn Pieters,如果没有你,我不会这样做,所以我接受你的回答。但是,请从我在您的答案中提供的链接中添加答案,这样如果其他人遇到同样的问题会更清楚。干杯! (2认同)