2
我正在使用hp on demand API,它将以正式查询的形式返回一个对象。未定义的逻辑出错
var obj = {
"positive": [
{
"sentiment": "love",
"topic": null,
"score": 0.8053406931054015,
"original_text": "I love you",
"original_length": 10,
"normalized_text": "I love you",
"normalized_length": 10
}
],
"negative": [],
"aggregate": {
"sentiment": "positive",
"score": 0.8053406931054015
}
}
,它将返回对象这样的负查询
{
"positive": [],
"negative": [
{
"sentiment": "hate",
"topic": null,
"score": -0.8748623139495181,
"original_text": "I hate you",
"original_length": 10,
"normalized_text": "I hate you",
"normalized_length": 10
}
],
"aggregate": {
"sentiment": "negative",
"score": -0.8748623139495181
}
}
,我试图财产normalized_text分配到文本,但似乎是用不确定的逻辑错误。这里是我的代码
var arr = ["I hate you", "I love you", "I miss you"];
var emotions = [];
for(var i=0; i<arr.length; i++){
//console.log(arr[i]);
$.ajax({
url: "https://api.idolondemand.com/1/api/sync/analyzesentiment/v1?text="+arr[i]+"&apikey=e3b26b74-bla"
})
.done(function(data) {
var obj = data;
//emotions.push(obj.aggregate.sentiment);
var text;
if(typeof obj.positive[0].normalized_text === "undefined"){
text = obj.negative[0].normalized_text;
}else{
text = obj.positive[0].normalized_text;
}
console.log(text);
console.log(obj.aggregate.sentiment);
});
}
我的错误是cannot read normalized_text of undefined
'obj.positive [0]'尚未定义,导致对undefined.normalized_text的解析尝试,这是一个错误,因为undefined不是一个对象。 – Siguza
您可能必须在引用其对象文字之前解析JSON数据。 – Sajal
你可以缩小这个例子吗? –