gpt4 book ai didi

python - json.dump - UnicodeDecodeError : 'utf8' codec can't decode byte 0xbf in position 0: invalid start byte

转载 作者:太空狗 更新时间:2023-10-29 18:01:33 24 4
gpt4 key购买 nike

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

  • key - 事件 ID

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

现在,我想把这张 map 写到一个 json 文件中。我试过这个:

with open('events_map.json', 'w') as out_file:
json.dump(data, out_file, indent = 4)

但这给了我错误:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xbf in position 0: invalid start byte

现在,我也试过:

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' codec can't decode byte 0xbf in position 0: invalid start byte

我也尝试过:

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' codec can't decode byte 0xbf in position 3114: ordinal not in range(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: must be unicode, not 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 编码的.

你必须替换这个值;通过替换 UTF-8 编码的值,或者通过使用对该值的正确编码仅解码该值来将其解码为 unicode 对象:

data['142'] = data['142'].decode('latin-1')

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

关于python - json.dump - UnicodeDecodeError : 'utf8' codec can't decode byte 0xbf in position 0: invalid start byte,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25122371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com