RandyV
RandyV

Reputation: 243

json.load() function give strange 'UnicodeDecodeError: 'ascii' codec can't decode' error

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' codec can't decode byte 0xc2 in position > 85298: ordinal not in range(128)

Here is the full error message:

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)

Here is my code:

import json
from pprint import pprint

with
open("/Users/.../KanyeAllSongs.txt") as data_file:
    data=json.load(data_file)

pprint(data)

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?

Upvotes: 24

Views: 35160

Answers (2)

mrvol
mrvol

Reputation: 2963

found it on Google. In my case, all ended up with:

open("/Users/.../KanyeAllSongs.txt", "rb") as data_file:
   data=json.load(data_file)

I added rb to open the file in binary mode.

Upvotes: 0

Konstantin
Konstantin

Reputation: 25339

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)

Upvotes: 53

Related Questions