I'm passing the following data set to my controller in JSON format:
[
{id: 0, exercises: [15, 18]},
{id: 1, exercises: [33, 35]}
]
This is received in my controller where I have to following code to display it temporarily:
arr = params["_json"]
binding.pry
This gives me the following output in the pry console:
[3] pry(#<ProgramsController>)> arr
=> [<ActionController::Parameters {"id"=>0, "exercises"=>[16, 7, 18]} permitted: false>,
<ActionController::Parameters {"id"=>1, "exercises"=>[14, 15]} permitted: false>]
I can then iterate this by going through arr[0] and arr[1], but how do I get the exercises that lie within these indexes?
So I can do something like this.
arr.each do |x|
prog = Program.create(x ...)
x.each do |exercise|
prog.exercises.create(exercise_id: exercise.id)
end
end
Hope someone can help me out handling this data. Thanks!
尝试使用 JSON.parse :)
arr = JSON.parse params["_json"]
The solution was quite simply: arr[0]["exercises"]
No parsing needed, thanks tho :)
To iterate over JSON in Rails. Try the following:
<ul>
arr.each do |a|
<li><%= a[id] %></li>
<li><%= a[exercises] %></li>
end
</ul>
OR
you can also try
@result = JSON.parse(HTTParty.get(your_url).body)
@result["arr"].each do |key, value|
puts key
puts value
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.