Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access JSON in Rails?

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?

like image 904
Jesse Crockett Avatar asked Dec 20 '22 07:12

Jesse Crockett


1 Answers

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"
like image 127
Jordan Running Avatar answered Dec 24 '22 02:12

Jordan Running