【问题标题】:Analyzing json using Watson API Nodejs使用 Watson API Nodejs 分析 json
【发布时间】:2017-10-08 07:58:51
【问题描述】:

我想分析我使用 Watson 的音调分析器动态创建的 JSON 文件。我想让它读取文件,然后分析它。

如何让tone_analyzer.tone 方法读取文件?谢谢你。

app.get('/results', function(req, res) {

    // This is the json file I want to analyze
    fs.readFile('./output.json', null, cb);

    function cb() {
        tone_analyzer.tone({
        // How can I pass the file here?
                text: ''
            },
            function(err, tone) {
                if (err)
                    console.log(err);
                else
                    console.log(JSON.stringify(tone, null, 2));
            });
        console.log('Finished reading file.')
    }
    res.render('results');
})

【问题讨论】:

    标签: json node.js web ibm-watson tone-analyzer


    【解决方案1】:

    您的回调缺少几个参数(错误、数据)(有关详细信息,请参阅the node fs documentation)。数据是您文件的内容,并且会发送到您发送文本的位置。

    试试这样的:

    app.get('/results', function(req, res) {
    
        // This is the json file I want to analyze
        fs.readFile('./output.json', 'utf8', cb);
    
        function cb(error, data) {
            if (error) throw error;
            tone_analyzer.tone({
            // How can I pass the file here?
                    text: data
                },
                function(err, tone) {
                    if (err)
                        console.log(err);
                    else
                        console.log(JSON.stringify(tone, null, 2));
                });
            console.log('Finished reading file.')
        }
        res.render('results');
    })
    

    【讨论】:

    • 我做了var data = fs.readFile('./output.json', null, cb);并在回调函数上传递了data,但它仍然输出error: 'No text given'
    • @agomez 这行不通,因为 fs.readFile 不返回任何内容。如果您在上面看到我的代码,我将 data 参数添加到您的回调中,cb。在那里我将数据直接发送到音调分析器。此外,您可能需要将“utf8”选项添加到 readFile。您还可以在路由中添加一个名为 text 的变量,并将音调分析器与 readFile 函数分开。
    • 感谢 Aldo 的提示,我在上面添加了答案。
    【解决方案2】:

    感谢用户 Aldo Sanchez 的提示。我首先将输入转换为 JSON,因为 fs 以缓冲区数据的形式返回它。此外,我让它在键/值对中搜索特定值并返回该内容,而不是返回整个字符串。这可以直接输入到 Watson 的音调分析器中。

    var data = fs.readFileSync('./output.json', null);
    
        JSON.parse(data, function(key, value) {
    
            if (key == "message") {
                cb(value);
            }
    
            function cb(value, err) {
                if (err) throw err;
    
                tone_analyzer.tone({
                        text: value
                    },
                    function(err, tone) {
                        if (err)
                            console.log(err);
                        else
                            console.log(tone);
                    });
    
            }
            console.log('Finished reading file.')
        });
    

    【讨论】:

      猜你喜欢
      • 2019-11-02
      • 2015-03-16
      • 1970-01-01
      • 2016-04-17
      • 2018-11-10
      • 2013-03-11
      • 1970-01-01
      • 2011-08-11
      • 1970-01-01
      相关资源
      最近更新 更多