使用 Watson API Nodejs 分析 json



我想分析一个我用 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');
})

您的回调缺少几个参数(错误、数据((有关更多信息,请参阅节点 fs 文档(。数据是您文件的内容,会转到您发送文本的位置。

尝试这样的事情:

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');
})

感谢用户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.')
    });

最新更新