请允许我在前言中说我确实看过.parse和如何使用.stringify,但没有任何效果。
在我的代码中,基于IBM的自然语言处理(https://www.ibm.com/watson/developercloud/natural-language-understanding/api/v1/?node#post-analyze),我有以下部分:
var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js');
var natural_language_understanding = new NaturalLanguageUnderstandingV1({
'username': 'f3550111-bd50-4e5f-8d44-8f0cc493c05e',
'password': 'XSG0rEW0UOlB',
'version_date': '2017-02-27'
});
var parameters = {
'text': 'A most interesting and amusing text indeed, about as amusing as IBMs godawful documentations',
'features': {
'entities': {
'emotion': true,
'sentiment': true,
'limit': 2
},
'keywords': {
'emotion': true,
'sentiment': true,
'limit': 2
}
}
}
我按照示例代码对响应进行字符串化,如下所示:
function calculateSentiment() {
natural_language_understanding.analyze(parameters, function(err, data) {
if (err)
console.log('error:', err);
else {
var myData = JSON.stringify(data, null, 2);
//console.log(myData[0][0][0]);
//var json = JSON.stringify(JSON.parse(data));
//console.log("Score: " + json);
//var prsed = (JSON.parse(data));
console.log("Parsed: " + myData);
}
}
);
}
正如您所看到的,我收到的所有评论都是我尝试解析的。如果我只是打印数据,我得到的只是[object Object]。我该如何正确解析这些数据? stringify的相应结果是(“Parsed:”部分来自我自己的控制台输出):
Parsed: {
"keywords": [
{
"text": "amusing text",
"sentiment": {
"score": 0.768903
},
"relevance": 0.98388,
"emotion": {
"sadness": 0.260734,
"joy": 0.407077,
"fear": 0.113361,
"disgust": 0.006258,
"anger": 0.028386
}
},
{
"text": "IBMs godawful documentation",
"sentiment": {
"score": 0
},
"relevance": 0.809662,
"emotion": {
"sadness": 0.156867,
"joy": 0.412954,
"fear": 0.094685,
"disgust": 0.082537,
"anger": 0.101907
}
}
],
"entities": [],
"language": "en"
}
Parsed: {
"keywords": [
{
"text": "amusing text",
"sentiment": {
"score": 0.768903
},
"relevance": 0.98388,
"emotion": {
"sadness": 0.260734,
"joy": 0.407077,
"fear": 0.113361,
"disgust": 0.006258,
"anger": 0.028386
}
},
{
"text": "IBMs godawful documentation",
"sentiment": {
"score": 0
},
"relevance": 0.809662,
"emotion": {
"sadness": 0.156867,
"joy": 0.412954,
"fear": 0.094685,
"disgust": 0.082537,
"anger": 0.101907
}
}
],
"entities": [],
"language": "en"
}
Parsed: {
"keywords": [
{
"text": "amusing text",
"sentiment": {
"score": 0.768903
},
"relevance": 0.98388,
"emotion": {
"sadness": 0.260734,
"joy": 0.407077,
"fear": 0.113361,
"disgust": 0.006258,
"anger": 0.028386
}
},
{
"text": "IBMs godawful documentation",
"sentiment": {
"score": 0
},
"relevance": 0.809662,
"emotion": {
"sadness": 0.156867,
"joy": 0.412954,
"fear": 0.094685,
"disgust": 0.082537,
"anger": 0.101907
}
}
],
"entities": [],
"language": "en"
}