I need to create a json-array with respect to my data. But in my data model, some of the fields are unnecessary and some of the fields name need to be changed for the json-array. Therefore I created a simple function to convert one object into a json format that I need to use :
def testMethod
{title: self.title, start: self.start_date, end: self.end_date, resource: Resource.find(self.resource_id).name}.to_json
end
So the output for this json object is:
{:title=>"Test", :start=>Thu, 27 Dec 2012 10:25:00 UTC +00:00, :end=>Thu, 27 Dec 2012 10:25:00 UTC +00:00, :resource=>"Resource1"}
But when I iterate all of my objects with the following loop:
@calJson = []
@calendars.each do |cal|
@calJson.push(cal.testMethod)
end
I'll have this useless string:
["{\"title\":\"Test\",\"start\":\"2012-12-27T10:25:00Z\",\"end\":\"2012-12-27T10:25:00Z\",\"resource\":\"Resource1\"}", "{\"title\":\"ikincii\",\"start\":\"2012-12-27T10:25:00Z\",\"end\":\"2012-12-27T10:25:00Z\",\"resource\":\"Resource2\"}", "{\"title\":\"b da son\",\"start\":\"2012-12-27T10:27:00Z\",\"end\":\"2012-12-27T10:27:00Z\",\"resource\":\"Resource1\"}"]
Whereas I want something like this:
[ { title: 'Lunch 12.15-14.45', start: new Date(y, m, d, 12, 15), end: new Date(y, m, d, 14, 45),
resource: 'resource1' }, { title: 'Meeting', start: new Date(y, m, d, 10, 30), end: new Date(y, m, d+4, 11, 00), resource: 'resource1' } ]
How should I do that ?
Thanks.
to_json
. It turns your hash into a JSON string. And you want to work with a hash. – Sergio Tulentsev Dec 27 '12 at 13:11