json.load()函数给出奇怪的'UnicodeDecodeError:'ascii'编解码器无法解码'错误 [英] json.load() function give strange 'UnicodeDecodeError: 'ascii' codec can't decode' error

查看:987
本文介绍了json.load()函数给出奇怪的'UnicodeDecodeError:'ascii'编解码器无法解码'错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用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.

我一直收到此错误消息.当我用google搜索时,没有结果.

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)

这是完整的错误消息:

回溯(最近一次通话最近):文件".../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(),文件>"/Library/Frameworks/Python.framework/Versions /3.5/lib/python3.5/encodings>/ascii.py,第26行,在解码返回codecs.ascii_decode(input,> self.errors)[0] UnicodeDecodeError:'ascii'编解码器无法解码字节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调用中指定编码.

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

这篇关于json.load()函数给出奇怪的'UnicodeDecodeError:'ascii'编解码器无法解码'错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆