首页 > 解决方案 > 为什么在 python 中使用 json 加载时会出现解码错误?

问题描述

我尝试打开一个 json 文件,但出现解码错误。我找不到解决方案。我怎样才能解码这些数据?

该代码给出以下错误:

UnicodeDecodeError:“utf-8”编解码器无法解码位置 3765 中的字节 0xf6:无效的起始字节

import json
url = 'users.json'
with open(url) as json_data:
     data = json.load(json_data)

标签: pythonjsonload

解决方案


这意味着您尝试解码的数据未以 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 之类的内容中


推荐阅读