gpt4 book ai didi

python - 如何为 json.load 设置正确的编码

转载 作者:行者123 更新时间:2023-12-01 08:00:51 38 4
gpt4 key购买 nike

我一直在尝试以这种方式加载 json:

data = json.load(f)

由于某些原因,JSON 采用 windows1251 编码。因此尝试打开它会导致错误:

File "./labelme2voc.py", line 252, in main
data = json.load(f)
File "/home/dex/anaconda3/lib/python3.6/json/__init__.py", line 296, in load
return loads(fp.read(),
File "/home/dex/anaconda3/lib/python3.6/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 81: invalid continuation byte

我该如何解决这个问题? JSON 加载没有这样的选项来指定编码

最佳答案

试试这个:

import json

filename = ... # specify filename here

with open(filename, encoding='cp1252') as f:
data = json.loads(f.read())

关于python - 如何为 json.load 设置正确的编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55740353/

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