使用Watson API Nodejs分析json

我想分析一个我用Watson的音调分析器dynamic创build的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'); }) 

你的callback缺less一些参数(错误,数据)(更多信息参见节点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的提示。 我把input转换成JSON,因为fs是以缓冲区数据的forms返回的。 此外,我让它search键/值对中的具体值,并返回该内容,而不是返回整个string。 这可以直接input沃森的音调分析仪。

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