在node.js中定义JSON

iszxjhcz  于 2023-03-13  发布在  Node.js
关注(0)|答案(1)|浏览(209)

所以我试着在node.js中创建一个Alexa技能--然而,我似乎不知道如何定义json元素。我需要连接所有元素,在本例中,它们是来自新闻API的标题。我将它们都用console.logg'ed进行了记录,它工作正常。但我所要做的就是弄清楚如何将“title”设置为变量。如何将“title”设置为变量以包含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();
};
6pp0gazn

6pp0gazn1#

map迭代articles数组,然后可以在以后将它们连接起来。

var titles = body.articles.map(function(article) {
  return article.title;
});
  • 注意:如果任何标题未定义,将显示在联接中。*
    **更新:**根据您评论中的要点,您可以执行以下操作:
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(''));
      }
    });

  }
};

相关问题