json.load() 函数给出奇怪的 'UnicodeDecodeError: 'ascii' codec can't decode' 错误 [英] json.load() function give strange 'UnicodeDecodeError: 'ascii' codec can't decode' error
问题描述
我正在尝试使用 python .loads() 函数读取保存在文本文件中的 JSON 文件.稍后我将解析 JSON 以获取特定值.
I'm trying to read a JSON file I have saved in a text file using the python .loads() function. I will later parse the JSON to obtain a specific value.
我不断收到此错误消息.当我谷歌它时,没有结果.
I keep getting this error message. When I google it, there are no results.
UnicodeDecodeError: 'ascii' 编解码器无法解码位置 >85298 中的字节 0xc2:序号不在范围内 (128)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position >85298: ordinal not in range(128)
这里是完整的错误信息:
Here is the full error message:
回溯(最近一次调用):文件.../FirstDegreeKanyeScript.py",>第 10 行,在 data=json.load(data_file) 文件 >/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/in>it.py",第 265 行,在加载返回加载(fp.read(), File >"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/encodings>/ascii.py", line 26, in decode return codecs.ascii_decode(input, >self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 >在位置 85298:序号不在范围内 (128)
Traceback (most recent call last): File ".../FirstDegreeKanyeScript.py", >line 10, in data=json.load(data_file) File >"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/in>it.py", line 265, in load return loads(fp.read(), File >"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/encodings>/ascii.py", line 26, in decode return codecs.ascii_decode(input, >self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 >in position 85298: ordinal not in range(128)
这是我的代码:
import json
from pprint import pprint
with
open("/Users/.../KanyeAllSongs.txt") as data_file:
data=json.load(data_file)
pprint(data)
我已经尝试在 json.load
下添加 data.decode('utf-8')
,但我仍然遇到相同的错误.
I've tried adding data.decode('utf-8')
under the json.load
, but I still get the same error.
任何想法可能是什么问题?
Any ideas what could be the issue?
推荐答案
在 open
调用中指定编码.
Specify the encoding in the open
call.
# encoding is a keyword argument
open("/Users/.../KanyeAllSongs.txt", encoding='utf-8') as data_file:
data=json.load(data_file)
这篇关于json.load() 函数给出奇怪的 'UnicodeDecodeError: 'ascii' codec can't decode' 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!