json.load()函数出现了奇怪的'UnicodeDecodeError: 'ascii' codec can't decode'错误。

22
我正在尝试使用Python的.loads()函数读取我保存在文本文件中的JSON文件。我将稍后解析JSON以获取特定的值。
我一直收到这个错误消息。当我在谷歌上搜索时,没有任何结果。
错误消息的完整内容如下:
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/__init__.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'),但仍然遇到相同的错误。
有什么想法是什么问题?

你使用的是哪个版本的Python?文件使用的是哪种编码? - ZetaRift
2个回答

52

open调用中指定编码方式。

# encoding is a keyword argument
open("/Users/.../KanyeAllSongs.txt", encoding='utf-8') as data_file:
    data=json.load(data_file)

1
@Alik 我收到了以下错误信息:open('filename.js', encoding='utf-8') as data_file: ^ SyntaxError: 无效的语法 - Fight Fire With Fire
@FightFireWithFire - 待会儿就会更新(正在等待同行审核:http://stackoverflow.com/review/suggested-edits/16132026) - neverendingqs
1
可能应该使用 with open(...) as ... - Johnny Thunderman

0
在Google上找到了。在我的情况下,一切都结束了。
open("/Users/.../KanyeAllSongs.txt", "rb") as data_file:
   data=json.load(data_file)

我在打开文件时添加了rb以二进制模式打开文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接