How to access JSON in Rails?

匿名 (未验证) 提交于 2019-12-03 08:57:35

问题:

I have the following JSON params.

Started POST "/tickets/move.json" for ::1 at 2015-01-30 15:30:13 -0600 Processing by TicketsController#move as JSON   Parameters: {"_json"=>[{"id"=>"1", "col"=>1, "row"=>1}, {"id"=>"2", "col"=>2, "row"=>2}, {"id"=>"3", "col"=>2, "row"=>1}, {"id"=>"4", "col"=>4, "row"=>1}, {"id"=>"5", "col"=>5, "row"=>1}], "ticket"=>{}}

How can I access them, as I would with regular rails params?

回答1:

That's a regular params hash. Rails is usually smart enough to decode a JSON request and put the resulting object in params for you, and the hashrockets (=>) are a dead giveaway that it's a Ruby hash and not JSON. Formatted more nicely it looks like this:

{ "_json"  => [ { "id" => "1", "col" => 1, "row" => 1 },                 { "id" => "2", "col" => 2, "row" => 2 },                 # ...               ],   "ticket" => {} }

You'll access it like any other Hash:

p params["_json"] # => [ {"id"=>"1", "col"=>1, "row"=>1}, #      {"id"=>"2", "col"=>2, "row"=>2}, #      ... #    ]  p params["_json"][0] # => {"id"=>"1", "col"=>1, "row"=>1}  p params["_json"][0]["id"] # => "1"  p params["ticket"] # => {}

It ought to be a HashWithIndifferentAccess, actually, so you should be able to use symbol keys as well:

p params[:_json][0][:id] # => "1"


转载请标明出处:How to access JSON in Rails?
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!