0

下面是我的代码,我在其中解析了一个 json 文件并在循环中用于“for”循环,以便将其打印到控制台上

process.env.DEBUG = 'actions-on-google:*';
const apikey = "xxxxxx";
const https = require('https');
const ActionsSdkApp = require("actions-on-google");
const DialogflowApp = require('actions-on-google').DialogflowApp;
const app = new ActionsSdkApp({request, response});
//ActionsSdkApp({request, response} vs  DialogflowApp({ request: req, response: res })?????? which one do I use????
function responseHandler(app) {
    var topic = app.getArgument('topic');
    https.get(`https://example.com/${topic}?apiKey=${apikey}`, (res) => {
        let body = "";
        res.on('data', data => {
            console.log('Reading Data');
            body += data.toString();
        });
        res.on('end', () => {
            try {
                const profile = JSON.parse(body);
                for(let i = 0; i<profile.data.length;i++) {
                    console.log(" description: " + profile.data[i].description + " title: " + profile.data[i].title + ); // in the json file there are vales called "description" and "title" that I want on my list 
            }} catch (e) {
            app.ask("Sorry, I was unable to load information. Please repeat the search term.");
            console.error("error: " + e.message);
        }
    });
})

}

我正在按照谷歌文档的操作示例,我正在尝试创建一个包含我的 json 文件中所有 json 对象的列表,但我遇到了困难。以下是我的尝试:

function list () {
    const app = new ActionsSdkApp({request, response});
    app.askWithList('Here are a few things I found. Pick one that looks interesting',
        app.buildList('Things to learn about')
    // i want add my loop here....but I how would I add it probably?? for(let i = 0; i<profile.data.length;i++)
            .addItems
                .setTitle(" title: " + profile.data[i].title)
                .setDescription(" description: " + profile.data[i].description)
    );
};

任何人都可以提供任何建议来帮助我建立列表吗?另外,我是导入 actionsdk 库还是 dialogflow 库?

4

1 回答 1

1

对于初学者,您使用哪个库取决于您使用的工具集。如果您使用的是 Dialogflow - 使用该库。如果您使用的是 Actions SDK - 请改用那个。(除非您有充分的理由使用 Actions SDK,否则如果您不确定,您可能应该使用 Dialogflow 库。)

app.buildList()命令返回一个List,因此您可以使用addItem()将项目添加到该列表中。没有什么说您必须将它们链接起来,您可以addItem()在循环中一次调用该列表。我没有对此进行测试,但您的代码可能类似于:

var list = app.buildList('Things to learn about');
for( let i=0; i<profile.data.length;i++ ){
  var title = profile.data[i].title;
  var desc  = profile.data[i].description;
  var key   = "key-"+i;  // This is what you'll get from the user
  var alias = [];        // This really should be what the user can say that is equivalent
  var item = app.buildOptionItem( key, alias )
    .setTitle( title )
    .setDescription( desc );
  list.addItem( item );
}
app.askWithList( 'Pick one', list );
于 2017-11-20T15:21:22.480 回答