开发者

Ruby + JSON + Regexp

开发者 https://www.devze.com 2023-01-12 00:38 出处:网络
I\'m working on a RoR project and I am passing a JSON object to a script.Specifically, a list of events to a jquery calendar.

I'm working on a RoR project and I am passing a JSON object to a script. Specifically, a list of events to a jquery calendar.

First I get the necessary events from active record and convert them to json:

@events = CalendarEvent.find(:all, :conditions => ["mentor_id = ?", current_user]).to_json(:only => [:id, :availability, :starts_at, :ends_at])

This returns the following:

[{"calendar_event":{"starts_at":"2010-08-14T17:15:00Z","id":1,"availability":true,"ends_at":"2010-08-14T17:45:00Z"}},
 {"calendar_event":{"starts_at":"2010-08-15T15:45:00Z","id":2,"availability":true,"ends_at":"2010-08-15T16:15:00Z"}},
 ...]

However, I am running into problems because the script is expecting the following format:

[{"starts_at":"2010-08-14T17:15:00Z","id":1,"availability":true,"ends_at":"2010-08-14T17:45:00Z"},
 {"starts_at":"2010-08-15T15:45:00Z","id":2,"availability":true,"ends_at":"2010-08-15T16:15:00Z"},
 ...]

At first I thought it would be a simple matter of popping the values from the separate hashes, and returning an array filled with those. However, it seems that everything in the array is one big string. So I was trying to get the necessary stuff using a regular expression. My best shot was:

@json = @events.scan(/\[\{\"calendar_event\":(\{.*\})\}\]*/)

But this returns something of the form:

[["{\"starts_at\":\"2010-08-14T17:15:00Z\",\"id\":1,\"availability\":true,\"ends_at\":\"2010-08-14T17:45:00Z\"}},{\"calendar_event\":{\"starts_at\":\"2010-08-15T15:45:00Z\",\"id\":2,\"availability\":true,\"ends_at\":\"2010-08-15开发者_运维问答T16:15:00Z\"}},..."]]

Any help would be appreciated.


ActiveRecord::Base.include_root_in_json = false

Have fun.

Reading documentation helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号