我正在尝试解析来自请求正文的json数据。我收到请求的正文如下:
{ 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 :(得分:1)
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。