使用Watson API节点分析json
我想分析我用Watson的音调分析器动态创建的JSON文件。我希望它读取文件,然后分析它 如何使tone_analyzer.tone方法读取文件?多谢各位使用Watson API节点分析json,json,node.js,web,ibm-watson,tone-analyzer,Json,Node.js,Web,Ibm Watson,Tone Analyzer,我想分析我用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_analy
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');
})
您的回调缺少几个参数(错误、数据)(有关更多信息,请参阅)。数据是文件的内容,它将放在发送文本的地方 试着这样做:
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以缓冲区数据的形式返回它。另外,我让它搜索键/值对中的特定值并返回该内容,而不是返回整个字符串。这可以直接输入到沃森的音调分析仪
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.')
});
我制作了
var data=fs.readFile('./output.json',null,cb)
并在回调函数上传递了数据
,但它仍然会输出错误:“未给出文本”
@agomez,因为fs.readFile不会返回任何内容。如果您看到上面的代码,我将data参数添加到您的回调cb中。在那里,我将数据直接发送到音调分析器。此外,您可能需要将“utf8”选项添加到readFile中。您还可以在路由中添加一个名为text的变量,并将音调分析器与readFile函数分开。