无法读取JSON响应,整数变成NULL

时间:2018-06-29 09:42:12

标签: javascript json node.js chatbot dialogflow

我正在Firebase中为Google的Dialogflow聊天机器人编写此实现代码。

我正在尝试获取 Count 的值,但它显示为空。

以下是API响应:

  

[{“ Count”:1385}]

这是我的代码:

function getCount(cloudFnResponse) {

    var pathString = "//someApiPath";
    console.log('Path string: ' + pathString);


    var request = https.get({
    //method:"GET",
    host: "//someApiHost",
    path: pathString
    }, function(response) {

        var json = "";
        console.log("Log1=> response is: " + response);
        response.on('data', function(chunk) {
            console.log("log2=> Received json response: " + chunk);
            json += chunk;

         });
         response.on('end', function() {
            var jsonData = JSON.parse(json);

            console.log("log3=> jsonData is: " + jsonData);
            var count = jsonData[0].Count;

            console.log("log4=> count is: " + JSON.stringify(count));

            var chat = "Count is " + count;
            console.log("log5=> chat is: " + chat);
            cloudFnResponse.send(buildChatResponse(chat));
         });

    });
}

我已经添加了调试日志,这是上面代码的输出日志:

log1=> response is: [object Object]
log2=> Received json response: [{"Count":null}]
log3=> jsonData is: [object Object]
log4=> bot count is: undefined
log5=> chat is: Count is undefined

我还想也许与API响应有关,整数部分:1385,不是用双引号引起来吗?

关于如何成功获取整数值的任何建议?它继续变为null。

1 个答案:

答案 0 :(得分:1)

根据API响应,像这样更新功能-

您应该使用Count而不是count,因为它返回的是Count

function getCount(cloudFnResponse) {

  var pathString = "//someApiPath";
  console.log('Path string: ' + pathString);


  var request = https.get({
    //method:"GET",
    host: "//someApiHost",
    path: pathString
  }, function(response) {

    var json = "";
    console.log("Log1=> response is: " + response);
    response.on('data', function(chunk) {
      console.log("log2=> Received json response: " + chunk);
      json += chunk;

    });
    response.on('end', function() {
      var jsonData = JSON.parse(json);

      console.log("log3=> jsonData is: " + jsonData);
      var Count = jsonData[0].Count;

      console.log("log4=> count is: " + JSON.stringify(Count));

      var chat = "Count is " + Count;
      console.log("log5=> chat is: " + chat);
      cloudFnResponse.send(buildChatResponse(chat));
    });

  });
}