2016-08-17 9 views
0

私はnode.jsでAlexaのスキルを作ろうとしていますが、json要素の定義方法を理解できないようです。私はすべての要素に参加する必要があります。この場合、ニュースAPIのタイトルです。私はそれらのすべてのconsole.logg'edと動作しているが、私は "タイトル"変数を作る方法を把握する必要があります。 JSONファイルのすべてのタイトルを含めるにはどうすれば "タイトル"を変数にすることができますか?その後、彼らは後に結合することができるmaparticlesアレイ全体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

反復:ここに私のコードです。

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アップデートをチェックしてください。 –