7

I have a ruby application and I need to receive a JSON from a client. Receiving a JSON is just like receiving a string? I just have to do something like:

information = params[:json_data] data_parsed = JSON.parse(information) 

That's all or I have to do something different when getting a JSON? The sender has to send me that like string?

Thanks!

2
  • but is there any other way of doing these? Or just getting it with params? Commented Aug 31, 2012 at 21:17
  • You're doing it right already. The payload of the POST request will always be inside your params Hash as a String (Or a nested Hash, but the values will always be Strings). It makes no difference what the actual datatype or data structure is. The same way you can't send 1 as an Integer, you can't send {json: true} as some kind of JSON object or Hash. Commented Sep 1, 2012 at 1:01

2 Answers 2

28

What you are describing is OK, but it implies that there is a param named json_data. If you instead mean that the entire POST body is nothing but the JSON, then you want to look at request.raw_post. You'd end up with something like this:

information = request.raw_post data_parsed = JSON.parse(information) 
Sign up to request clarification or add additional context in comments.

Comments

17

The official document says,

If the "Content-Type" header of your request is set to "application/json", Rails will automatically load your parameters into the params hash, which you can access as you would normally.

So for example, if you are sending this JSON content:

{ "company": { "name": "acme", "address": "123 Carrot Street" } } 

Your controller will receive params[:company] as { "name" => "acme", "address" => "123 Carrot Street" }.

Also, if you've turned on config.wrap_parameters in your initializer or called wrap_parameters in your controller, you can safely omit the root element in the JSON parameter. In this case, the parameters will be cloned and wrapped with a key chosen based on your controller's name. So the above JSON POST can be written as:

{ "name": "acme", "address": "123 Carrot Street" } 

And, assuming that you're sending the data to CompaniesController, it would then be wrapped within the :company key like this:

{ name: "acme", address: "123 Carrot Street", company: { name: "acme", address: "123 Carrot Street" } } 

So, if you send/POST { "hello": "world"} to apples/, then params['apple'] will be the object for the Json payload.

class ApplesController < ApplicationController def create # params['apple'] is the object represents Json payload end end 

1 Comment

Do note that deep_munge will sometimes mess with params, see github.com/rails/rails/issues/13766

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.