2017-03-03 74 views
1

我正在尝试遍历通过我的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); 
    }) 
} 
+1

和你有什么问题 – user7417866

+3

JSON是文本数据。您需要解析它以将其转换为可以访问其属性的JS对象。 'var rData = JSON.parse(rBody);' – 2017-03-03 17:42:38

+1

“以JSON格式识别,或者识别为字符串” - JSON _is_字符串 – qxz

回答

2

看你的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." 
    } 
    }); 
} 
+1

我最终解决了一两个小时后,忘了回到这里。但这正是你在这里提到的。下一篇文章是结束工作的一小部分。只需要JSON.parse(rData); – Mike

+0

var rData = rBody; var rDataParsed = JSON.parse(rData); rDataParsed.data.items.forEach(函数(项目){ VAR日期= item.date; – Mike

+1

顺便说一句,非常感谢 – Mike