get the json in rails 3

amvis wrote in post #1055643:

I am trying to pass one json from one function. Here for the testing i
am
using mozilla Rest-client, where i pass the json as request body, so i
need to take that and pass into one function, but i could parse that
json
for getting the value, so how to get that into one variable.

*JSON*

*{"user": {"user_name":"user2"},"branch":{"branch_id":"1"}}*

Unless you do something to stop it Rails will parse your request body
content (i.e. your JSON) and provide the information in the standard
params hash (the same as is would for form data in the request body.

This is done by the rack middleware ActionDispatch::ParamsParser.

Give the JSON you show above you would have a single entry in the params
hash with the key :user and the value would be another hash containing
the rest of the JSON content.

Given this you can access the user_name and branch_id values as follows:

[1] pry(main)> params = { user: { user_name: "user2" }, branch: {
branch_id: "1" } }
=> {:user=>{:user_name=>"user2"}, :branch=>{:branch_id=>"1"}}

Above is what your JSON will look like after Rails middleware parses
your JSON.

[6] pry(main)> puts params[:user]
{:user_name=>"user2"}

The value of the the hash entry accessed via :user is another hash.

[7] pry(main)> puts params[:user][:user_name]
user2

Accesses the value of the :user_name key of the hash nested under :user.

[8] pry(main)> puts params[:branch][:branch_id]
1

Accesses the value of the :branch_id key of the hash nested under
:branch.

Hope that helps clear things up for you.