简体   繁体   中英

How to iterate through a JSON array in Rails

I am having some trouble iterating through my JSON array. I want to set a certain Schedule based on what the client sends to the server.

The JSON from the client will be sent in this format:

{
"Schedule": 
  {
    "monday": [
        12,
        15
    ]
  , 
  "tuesday": [
        10,
        16
    ]
  }
}

I would like to iterate like this:

params[:Schedule].each do |day| do
   day.each do |time|
    schedule.add_recurrence_rule(IceCube::Rule.weekly.day(0).hour_of_day(time))
   end
end

However this doesn't work, since when I print params[:Schedule].each it prints out monday, 12, 15, tuesday, 10, 16 etc....

Does anyone have a solution for this?

params["Schedule"] gets an hash, not an array. So your block will have a key (the day as a name) and an array

params["Schedule"].each do |day_name, day_schedule|
  # to do
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM