1

Im getting a Unicode error when running this test script.

import urllib
import json

movieTitle = "Bee Movie"
title = movieTitle.replace(" ", "+")
year = ""
omdbAPI = "http://www.omdbapi.com/?t={}&y={}&plot=short&r=json".format(
    title, year)
print (omdbAPI)
response = urllib.urlopen(omdbAPI)
data = json.loads(response.read())
valid_data = data["Response"]
print ("This data is: " + valid_data)

if valid_data == "True":
    print data["Title"]
    print data["Year"]
    print data["Plot"]
    print data["Rated"]
    print data["Released"]
    print data["Runtime"]
    print data["Genre"]
    print data["Director"]
    print data["Writer"]
    print data["Actors"]
    print data["Language"]
    print data["Country"]
    print data["Awards"]
    print data["Poster"]
    print data["Metascore"]
    print data["imdbRating"]
    print data["imdbVotes"]
    print data["imdbID"]
    print data["Type"]
    print data["Response"]
elif valid_data == "False":
    print ("This data is: " + valid_data)
else:
    raise ValueError("The information was not found")

Error :

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 19: ordinal not in range(128)

I guess its because one off the actors seams to have a é character.

I figured out that I could put .encode('utf8') after print data["Actors"] but it don't seams like the smartest thing to do. I mean a random letter could occur on more places then on actor. And seams odd to go put .encode('utf8') after every instance

UPDATE :

Traceback (most recent call last):
  File "/Volumes/postergren_projectDrive/Projekt/programmingSandbox/python/courses/udacity/Programming Foundations with Python/moveis/Advance/media.py", line 25, in <module>
    print data["Actors"]
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 19: ordinal not in range(128)
[Finished in 0.1s with exit code 1]
[shell_cmd: "python" -u "/Volumes/postergren_projectDrive/Projekt/programmingSandbox/python/courses/udacity/Programming Foundations with Python/moveis/Advance/media.py"]
[dir: /Volumes/postergren_projectDrive/Projekt/programmingSandbox/python/courses/udacity/Programming Foundations with Python/moveis/Advance]
[path: /usr/bin:/bin:/usr/sbin:/sbin]
martineau
  • 119,623
  • 25
  • 170
  • 301
Petter Östergren
  • 973
  • 4
  • 14
  • 27
  • 1
    Just the error message is often not enough. At least say what line it occurs on...or better yet, include the entire backtrace (all in your question, not down here in comments). – martineau Feb 18 '17 at 19:58
  • @martineau oh, that's true. Thanks. I have added the traceback, its line 25. – Petter Östergren Feb 18 '17 at 21:48

2 Answers2

1

Try this at the begining of your code:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
Mohamad Ibrahim
  • 5,085
  • 9
  • 31
  • 45
0

You can do this:
for key in data.keys() data[key] = data[key].encode('utf8')