为什么在 python 中使用 json 加载时会出现解码错误?
why do i get a decode error when using json load in python?
我尝试打开 json 文件,但出现解码错误。我找不到解决方案。我如何解码这些数据?
代码报错如下:
UnicodeDecodeError:'utf-8'编解码器无法解码位置 3765 中的字节 0xf6:起始字节无效
import json
url = 'users.json'
with open(url) as json_data:
data = json.load(json_data)
这意味着您尝试解码的数据未以 UTF-8 编码
编辑:
您可以在使用 json 加载它之前对其进行解码,方法如下:
with open(url, 'rb') as f:
data = f.read()
data_str = data.decode("utf-8", errors='ignore')
json.load(data_str)
https://www.tutorialspoint.com/python/string_decode.htm
请注意,您将在此过程中丢失一些数据。一种更安全的方法是使用与编码 JSON 文件相同的解码机制,或者将原始数据字节放入类似 base64
的格式中
我尝试打开 json 文件,但出现解码错误。我找不到解决方案。我如何解码这些数据?
代码报错如下:
UnicodeDecodeError:'utf-8'编解码器无法解码位置 3765 中的字节 0xf6:起始字节无效
import json
url = 'users.json'
with open(url) as json_data:
data = json.load(json_data)
这意味着您尝试解码的数据未以 UTF-8 编码
编辑:
您可以在使用 json 加载它之前对其进行解码,方法如下:
with open(url, 'rb') as f:
data = f.read()
data_str = data.decode("utf-8", errors='ignore')
json.load(data_str)
https://www.tutorialspoint.com/python/string_decode.htm
请注意,您将在此过程中丢失一些数据。一种更安全的方法是使用与编码 JSON 文件相同的解码机制,或者将原始数据字节放入类似 base64
的格式中