2016-08-17 81 views
0

所以我想在node.js中做一個Alexa技能 - 但是,我似乎無法弄清楚如何定義json元素。我需要加入所有元素,在這種情況下,他們是來自新聞API的標題。我有他們所有console.logg'ed和它的作品,但我需要做的是弄清楚如何使「標題」變量。我怎樣才能讓「title」變量包含JSON文件中的所有標題。這裏是我的代碼:在node.js中定義JSON

var Alexa = require('alexa-sdk'); 
var request = require('request'); 

var APP_ID = "amzn1.ask.skill.36267067-d40c-460c-b07b-cc603b97be1b"; 
var url = "https://newsapi.org/v1/articles?source=googlenews&sortBy=top&apiKey=6e23e1ddb67e40cb93cf147718f18e36"; 


var handlers = { 
    'LaunchRequest': function() { 
     this.emit('NewsIntent'); 
    }, 

    // Get titles from JSON URL & Output it 
    'NewsIntent': function() { 

     request({ 
      url: url, 
      json: true 
     }, function (error, response, body) { 

      if (!error && response.statusCode === 200) { 
      console.log(body.articles[0].title); 
      console.log(body.articles[1].title); 
      console.log(body.articles[2].title); 
      console.log(body.articles[3].title); 
      console.log(body.articles[4].title); 
      console.log(body.articles[5].title); 
      console.log(body.articles[6].title); 
      console.log(body.articles[7].title); 
      console.log(body.articles[8].title); 
      console.log(body.articles[9].title); 

///// I need help here!!!!! ----> 
     /// need to define title, so I can speech emit it below. 

      this.emit(':tellWithCard', title.join('')); 

      } 
     }); 

    } 
}; 


exports.handler = function(event, context, callback) { 
    var alexa = Alexa.handler(event, context); 
    alexa.APP_ID = APP_ID; 
    alexa.registerHandlers(handlers); 
    alexa.execute(); 
}; 

回答

0

遍歷articles陣列map那麼他們可以在以後加入。

var titles = body.articles.map(function(article) { 
    return article.title; 
}); 

注意:如果任何標題未定義,將顯示在連接中。

UPDATE:基於對您的評論的要點,你可以這樣做:

var handlers = { 
    'LaunchRequest': function() { 
    this.emit('NewsIntent'); 
    }, 

    // Get titles from JSON URL & Output it 
    'NewsIntent': function() { 

    request({ 
     url: url, 
     json: true 
    }, function(error, response, body) { 
     var titles; 
     if (!error && response.statusCode === 200) { 
     console.log(body.articles[0].title); 
     console.log(body.articles[1].title); 
     console.log(body.articles[2].title); 
     console.log(body.articles[3].title); 
     console.log(body.articles[4].title); 
     console.log(body.articles[5].title); 
     console.log(body.articles[6].title); 
     console.log(body.articles[7].title); 
     console.log(body.articles[8].title); 
     console.log(body.articles[9].title); 

     titles = body.articles.map(function(article) { 
      return article.title; 
     }); 

     this.emit(':tellWithCard', titles.join('')); 
     } 
    }); 

    } 
}; 
+0

因此,將這項工作?感謝您的幫助https://gist.github.com/samayshamdasani/f6e2ce356c7ccd13fc0c8e3c919e929c –

+0

@SamayShamdasani檢查出更新。 –