如何使用一个大数组返回JSON对象作为JSON对象?

时间:2014-07-17 15:56:00

标签: javascript arrays json node.js spookyjs

我们在SpookyJS中有一个函数,当JSON object中调用GET方法时,它返回array只包含stringsnodeJS JSON object个函数。我们希望它返回array strings array转换为JSON objects AngularJS

注意:如果更改了任何内容,我们最终希望能够在res.send({reviewCount: reviews.length, reviews: reviews}); 中使用这些对象。

这是功能:

{
    "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"
    ]
}

以下是它的回报:

{
    "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!"}
    ]
}

我们想要回归:

JSON.stringify()

我们尝试使用res.send({reviewCount: reviews.length, reviews: JSON.stringify(reviews)}); ,但它只是将所有内容转换为一个JSON对象:

{{1}}

1 个答案:

答案 0 :(得分:0)

我最终搞清楚了。这是我做的:

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);
    });