1

I'm having a bit of trouble wrapping my head around some JSON stuff. Namely, I'm trying to retrieve a string from a json response received from the google translate api i'm querying.

  var translator = function () {
  for (var i = 0; i < result.length; i++)
  {
    //Construct URI
    var source =
      'https://www.googleapis.com/language/translate/v2?' +
      'key=MY-API-KEY-REMOVED-ON-PURPOSE&' +
      'source=en&' +
      'target=fr&' +
      'q=' +
      result[i][1]; //looping over an array, no problem there



      //Receive response from server
    var to_Translate =new XMLHttpRequest();
    to_Translate.open("GET",source,false);
    to_Translate.send();
    var translated = to_Translate.responseText;

    JSON.parse(translated);
    translated = translated.data.translations[0].translatedText;

    console.log(translated);


  }
};


translator();

Where

console.log(translated);

yields

 {
 "data": {
  "translations": [
   {
    "translatedText": "some stuff that's been translated"
   }
  ]
 }
}

My question is: how can i access the value of translatedText? I've tried:

translated.data.translations[0].translatedText;

But it doesn't seem to work. When I console.log this i get

    Uncaught TypeError: Cannot read property 'translations' of undefined 
    translator 
(anonymous function)

Let me know what you guys think!

4

3 回答 3

1

那只是你必须用它来解析它的文本

JSON.parse(translated)

所以你可以访问它,例如,translated.data

更新

您得到的错误意味着translated.data未定义,您必须将解析分配给一个变量,否则它将永远无法工作,它不会就地修改它

var translated = JSON.parse(to_Translate.responseText);
于 2013-07-12T09:52:27.840 回答
0

是的,使用 translated.data.translations[0].translatedText;

希望它会正常工作。

于 2013-07-12T09:53:49.307 回答
0

很近!

translated.data.translations[0].translatedText;

translations是一个对象数组,并且您想要数组中translatedText第一个元素的属性。

更新

只是为了确认输出to_Translate.responseText是一个包含以下内容的字符串:

{
 "data": {
  "translations": [
   {   
    "translatedText": "some stuff that's been translated"
   }
  ]
 }
}

所以你应该能够做到:

var translated = to_Translate.responseText,
    parsed = JSON.parse(translated),
    text = parsed.data.translations[0].translatedText;

console.log(text);
于 2013-07-12T09:52:11.713 回答