Reputation: 720
I am trying to to parse json data from request body. The body I get in request is like :
{ members: '[{"ContactName":"abc","ContactNumber":"+92------","Turn":"28/04/2017","mData":0}]',
cid: '-Kl8Yhi-3qCQ4E-iDFj6',
committeedetails: '{"admin":"+923064664223","description":"xyz\\nMembers 1\\nPKR 10"}' }
and I get members from it as:
var body = req.body;
var members = body.members;
and console log for members is:
[{"ContactName":"abc","ContactNumber":"+92--------","Turn":"28/04/2017","mData":0}]
I want to iterate over this I have tried:
members.forEach(function(obj) { console.log("members",obj.id); });
Now issue is that I cant iterate over this json array. It throughs typo error :
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)
from some other questions I have also tried:
for(var i= 0; i<members.length; i++){
var obj = members[i];
console.log("members"+i, obj);
}
and :
for (var key in members){
console.log("members",key);
}
these always through members length about 100. and log each character in the array.
Can anybody here correct me to iterate over json array containing json objects?
Upvotes: 0
Views: 1110
Reputation: 598951
The value of your members
property is a string, while forEach
only exists on an array (and a Firebase Snapshot).
For the moment you can iterate over the data encoded in the string by calling JSON.parse()
on it:
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);
});
Work jsbin: https://jsbin.com/quboza/edit?js,console
But you really should figure out why the data is stored as a string, instead of as JSON.
Upvotes: 1