Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: expected string or buffer in Google App Engine's Python

I want to show the content of an object using the following code:

def get(self):
    url="https://www.googleapis.com/language/translate/v2?key=MY-BILLING-KEY&q=hello&source=en&target=ja"
    data = urllib2.urlopen(url)
    parse_data = json.load(data)
    parsed_data = parse_data['data']['translations']

    // This command is ok
    self.response.out.write("<br>")

    // This command shows above error
    self.response.out.write(str(json.loads(parsed_data[u'data'][u'translations'][u'translatedText'])))

But the error

TypeError: expected string or buffer

appears as a result of the line:

self.response.out.write(str(json.loads(parsed_data[u'data'][u'translations'][u'translatedText'])))

or

self.response.out.write(json.loads(parsed_data[u'data'][u'translations'][u'translatedText']))

UPDATE (fix):

I needed to convert from string to JSON object:

    # Convert to String
    parsed_data = json.dumps(parsed_data)

    # Convert to JSON Object
    json_object = json.loads(parsed_data)

    # Parse JSON Object
    translatedObject = json_object[0]['translatedText']

    # Output to page, by using HTML
    self.response.out.write(translatedObject)
like image 970
Huy Tower Avatar asked Aug 14 '13 04:08

Huy Tower


1 Answers

parse_data = json.load(data)
parsed_data = parse_data['data']['translations']

Those lines already did the json.load, and extracted 'data' and 'translations'. Then instead of:

self.response.out.write(str(
    json.loads(parsed_data)[u'data'][u'translations'][u'translatedText']))

you should:

self.response.out.write(str(
    parsed_data[u'translatedText']))
like image 85
Felipe Hoffa Avatar answered Oct 11 '22 12:10

Felipe Hoffa