我正在 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,没有用双引号引起来?
关于如何成功获取整数值有什么建议吗?它不断变成空。
最佳答案
根据 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));
});
});
}
关于javascript - 无法读取 JSON 响应,整数变为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51098833/