Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 715
RandyV Avatar asked Jan 28 '16 02:01

RandyV


1 Answers

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)
like image 126
Alik Avatar answered Sep 17 '22 05:09

Alik