TypeError: expected string or buffer in Google App Engine Python

I want to show the contents 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 a mistake

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 a string to a 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) 
+6
source share
3 answers

All I need is a conversion from String to a JSON object, as the following code:

 # 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) 
0
source
 parse_data = json.load(data) parsed_data = parse_data['data']['translations'] 

These lines have already executed json.load and extracted the β€œ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'])) 
+2
source

The urllib2.urlopen function returns an object similar to a file, not a string. You must read the answer first.

 url = "http://www.example.com/data" f = urllib2.urlopen(url) data = f.read() print json.loads(data) 
0
source

Source: https://habr.com/ru/post/951687/


All Articles