2017-03-03 73 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