我正在尝试遍历通过 get 请求返回的数据。我试图像使用 JSON 格式一样遍历它,但我对此很陌生,不确定它是否返回它以 JSON 格式识别的内容,或者它是否将其识别为字符串,这就是为什么我无法让它识别诸如 info.data.items 之类的东西。这是我使用节点的获取请求,基本身份验证。
这是从我的 get 请求返回的示例数据以及我实际尝试迭代的内容。
{"data":{"items":[{"date":"2017-02-02","revenue":111,"impressions":000},{"date":"2017-02-03","revenue":123,"impressions":0000,},"message":"Top 2 rows returned."}
function rData(key, secret, account_id) {
var https = require('https');
var options = {
host: 'api.urlhere.com',
port: 443,
path: 'path',
// authentication headers
headers: {
'Authorization': 'Basic ' + new Buffer(key + ':' + secret).toString('base64')
}
};
var request = https.get(options, function(res) {
var body = "";
res.on('data', function(data) {
body += data;
});
res.on('end', function() {
//console.log(body);
callNextFunction(body);
})
res.on('error', function(e) {
console.log("Got error: " + e.message);
});
});
}
然后这是我尝试迭代数据的下一个函数。通过这个函数后,我得到了错误,
TypeError: Cannot read property 'items' of undefined
function callNextFunction(rBody) {
var rData = rBody;
console.log("Data transfer sucessful: " + rData); // Works up to this point.
rData.data.items.forEach(function(info) {
var rev = info.revenue;
console.log("Revenue: " + rev);
})
}
最佳答案
查看您的 JSON 我可以看到以下问题
{"data":{"items":[{"date":"2017-02-02","revenue":111,"impressions":000},{"date":"2017-02-03","revenue":123,"impressions":0000,},"message":"Top 2 rows returned."} <-- this should probably be a ']' not sure
根据您的问题,我认为您想要访问数据的属性。 尝试以下操作
function callNextFunction(rBody) {
var rData = JSON.parse(rBody);
console.log("Data transfer sucessful: " + rData); // Works up to this point.
$.each(rData.data.items, function(i, info) {
if (info.date) {
//this info will contain the item with "date" "revenue"...
var rev = info.revenue;
console.log("Revenue: " + rev);
}
else if (info.message) {
// this is the information that contains the "message":"Top 2 rows returned."
}
});
}
关于javascript - 试图遍历一个节点得到休息返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42585234/