我正在构建一个聊天机器人,它根据用户的要求检索youtube链接。我将对话框用于机器人,使用nodejs编写代码。
现在,一切都很完美,但我的问题是从API响应中检索链接。使用console.dir(结果)显示如下:
[ { id: 'gWNUg_v25dw',
link: 'https://www.youtube.com/watch?v=gWNUg_v25dw',
kind: 'youtube#video',
publishedAt: '2017-08-24T14:00:11.000Z',
channelId: 'UCDZ56yQ05d_ikcwcTG9bAiA',
channelTitle: 'Code to Create',
title: 'How to make a Chatbot with Dialogflow - API.ai',
description: 'In this video, Google Developer Expert, Faisal Abid will show us how to create a chatbot with Google\'s latest API.ai API.ai can be integrated with multiple chat ...',
thumbnails: { default: [Object], medium: [Object], high: [Object] } } ]
我尝试过使用results.link检索链接,但我的问题是如何从响应块中检索链接?
search(txt1, opts, function(err, results) {
//var data1 = JSON.parse(results);
//srchRes = data1.link;
if(err) return console.log(err);
console.dir(results);
});
去掉上面的2行注释,console.dir(srchRes)返回此错误:
SyntaxError: Unexpected token u in JSON at position 0
发布于 2018-09-25 02:24:46
我们没有API调用代码逻辑,因此从这里开始,只能假定 results
是API的响应,并给出了响应的示例,然后我们看到results
是一个对象数组。
您的目标是到达数组中的link
特定对象的属性,这就是为什么JSON.parse(results)
没有意义的原因。
您应该能够通过简单地迭代对象results
数组来达到每个对象的results
属性。
for (const result of results) {
console.log(`the link : ${result.link}`)
}
https://stackoverflow.com/questions/52495273
复制相似问题