python - 为什么在 python 中使用 json 加载时会出现解码错误?
问题描述
我尝试打开一个 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 之类的内容中
推荐阅读
- java - Tomcat 文件加载
- r - 如何清理变量名称和属性在同一单元格中的数据?
- node.js - 从异步活动函数返回对象持久扩展 Azure Function Nodejs
- html - 是否可以通过仅使用 html 和 css 按下按钮来获得动画?
- python - Essentia MusicExtractor python:来自 AudioLoader 的警告
- python - 如何在脚本中的 pywinauto 之后运行 pytest
- graph - 可视化大型树状图
- css - 如何显示多选下拉边框并单击任何显示位置
- javascript - 为什么我的模态窗口会自动打开和关闭?
- c# - 每当我尝试从 IIS 浏览服务时,都会尝试加载格式不正确的程序