2017-05-27 144 views
0

我想解析來自請求正文的json數據。身體我要求得到的是這樣的:迭代jsonarray firebase雲功能

{ members: '[{"ContactName":"abc","ContactNumber":"+92------","Turn":"28/04/2017","mData":0}]', 
    cid: '-Kl8Yhi-3qCQ4E-iDFj6', 
    committeedetails: '{"admin":"+923064664223","description":"xyz\\nMembers 1\\nPKR 10"}' } 

,我得到的成員從它:

var body = req.body; 
var members = body.members; 

和控制檯日誌成員是:

[{"ContactName":"abc","ContactNumber":"+92--------","Turn":"28/04/2017","mData":0}] 

我想遍歷這個我試過了:

members.forEach(function(obj) { console.log("members",obj.id); }); 

現在問題是,我不能迭代這個json數組。它得來錯字錯誤:

TypeError: members.forEach is not a function 
    at exports.shareTurnWithMembers.functions.https.onRequest (/user_code/index.js:110:13) 
    at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:26:47) 
    at /var/tmp/worker/worker.js:638:7 
    at /var/tmp/worker/worker.js:622:9 
    at _combinedTickCallback (internal/process/next_tick.js:67:7) 
    at process._tickDomainCallback (internal/process/next_tick.js:122:9) 

從一些其他的問題,我也試過:

for(var i= 0; i<members.length; i++){ 
     var obj = members[i]; 
     console.log("members"+i, obj); 
    } 

和:

for (var key in members){ 
      console.log("members",key); 
     } 

這些始終貫穿成員長約100和記錄每一個字符陣列。

任何人都可以在這裏糾正我迭代包含json對象的json數組嗎?

回答

0

members屬性的值是一個字符串,而forEach僅存在於陣列(和Firebase快照)上。

因爲你可以通過它調用JSON.parse()遍歷字符串中的編碼數據的時刻:

var val = { members: '[{"ContactName":"abc","ContactNumber":"+92------","Turn":"28/04/2017","mData":0}]', 
    cid: '-Kl8Yhi-3qCQ4E-iDFj6', 
    committeedetails: '{"admin":"+923064664223","description":"xyz\\nMembers 1\\nPKR 10"}' }; 

var members = JSON.parse(val.members); 

members.forEach(function(member) { 
    console.log(member); 
}); 

工作jsbin:https://jsbin.com/quboza/edit?js,console

但你真的應該弄清楚爲什麼數據存儲爲一個字符串,而不是JSON。