We have a function in SpookyJS that returns a JSON object
that contains just one huge array
of strings
when a GET method is called on it in nodeJS
. We'd like it to return a JSON object
with the array
of strings
converted to an array
of JSON objects
.
Note: We eventually want to be able to use these objects in AngularJS
if that changes anything.
Here is the function:
res.send({reviewCount: reviews.length, reviews: reviews});
Here is what it returns:
{
"reviewCount": 96,
"reviews": [
"\nSean Steinman\nreviewed 2 weeks ago\n Fantastic Service\n",
"\nRyan Lundell\nreviewed in the last week\n Ask for Scott!\n• • •\n"
]
}
What we'd like to return:
{
"reviewCount": 96,
"reviews": [
{name: "Sean Steinman", date: "reviewed 2 weeks ago", review: "Fantastic Service"},
{name: "Ryan Lundell", date: "reviewed in the last week", review:"Ask for Scott!"}
]
}
We've tried to play around with JSON.stringify()
, but it just converts everything into one JSON object:
res.send({reviewCount: reviews.length, reviews: JSON.stringify(reviews)});
I ended up figuring it out. Here is what I did:
spooky.run(function(){
var reviewObj = {
reviewCount: reviews.length,
reviews: []
}
reviews.forEach(function(line){
//turn the string into an array
var review = line.split('\n');
});
//add the array elements to the object
reviewObj.reviews.push({name: review[0], date: review[1], reviewContent: review[2]});
});
this.echo('about to emit');
this.emit("gotReviews", reviewObj);
});