【问题标题】:Unable to read JSON response, integer turns into NULL无法读取 JSON 响应,整数变为 NULL
【发布时间】:2018-06-29 09:42:12
【问题描述】:

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

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

以下是 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。

【问题讨论】:

  • 响应似乎是一个数组,所以你应该做 var count = jsonData[0].count;此外,当你 JSON.stringify(Count) 有一个大写 C 而不是小写
  • 对外壳表示歉意,现在更正了。我实际上替换了原始变量名(以及 API 路径)以清除一些潜在的敏感信息。如果变量大小写正确,它仍然显示为 null。

标签: javascript json node.js chatbot dialogflow-es


【解决方案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));
    });

  });
}

【讨论】:

  • 谢谢,我按照建议更新了大小写,但正如您在该部分代码之前看到的那样,在“log2”中它已经显示为空。
  • @brian3415 表示您的 API 未返回 Count,请调试 API
  • 但是当我在浏览器中访问路径时,它会返回计数。
猜你喜欢
  • 2016-06-03
  • 1970-01-01
  • 2016-05-31
  • 1970-01-01
  • 2018-10-30
  • 2012-12-07
  • 1970-01-01
  • 1970-01-01
  • 2014-05-02
相关资源
最近更新 更多