在node.js中定义JSON
Defining JSON in node.js
所以我试图在node.js中制作Alexa技能-然而,我似乎无法弄清楚如何定义json元素。我需要连接所有元素,在本例中它们是来自新闻API的标题。我都有控制台。记录和它的工作,但所有我需要做的是弄清楚如何使"标题"一个变量。我怎么能使"标题"一个变量,包括所有的标题从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();
};
用map
迭代articles
数组,然后它们可以稍后连接。
var titles = body.articles.map(function(article) {
return article.title;
});
注意:如果任何标题未定义,将显示在join中。
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(''));
}
});
}
};
相关文章:
- 具有自定义json响应的Highcharts系列数据
- 使用Webhook在Slack上发布自定义JSON消息
- Angular 不返回我的自定义 JSON 文件
- 如何定义 JSON 对象值的默认值
- Javascript - 无法读取未定义 - json 的属性 'x'
- 通过传单中来自 csv 的数据定义 json 多边形的颜色
- 如何仅使用 JavaScript 的 stringify() 方法在第一级自定义 JSON 输出
- 加载自定义 json 文件 - 高图表.js
- Laravel PHP-从DB到PHP再到JS到HTML的自定义JSON对象
- 尝试检查未定义json对象的类型时出错
- 生成自定义JSON数组
- 动态定义JSON-can'I don’我没有发现我做错了什么
- 客户端未定义JSON服务类
- 烬RESTAdapter自定义JSON格式
- 更改的自定义JSON Ajax循环
- HighMap显示自定义json文件的问题
- 在d3.js的外部文件中未定义JSON数据
- 未定义JSON错误请求
- 从多个数组构建自定义JSON数组
- 如何使用自定义JSON(不是GeoJSON)与Highcharts地图