简体   繁体   中英

How to parse json of an incoming POST request in Rails?

I have the following problem. A web service is sending a JSON POST request to my app and I want to parse it.

I thought I just can access the params with

@var = params[:name_of_the_JSON_fields]

but it doesn't work. I see in my Heroku logs, that the request is done and that the parameters are there, but I just can't store them.

Does anyone have an idea?

When you post JSON (or XML), rails will handle all of the parsing for you, but you need to include the correct headers.

Have your app include:

Content-type: application/json

And all will be cool.

This answer may not be particular to this exact question, but I had a similar issue when setting up AWS SNS push notifications. I was unable to parse or even view the initial subscription request. Hopefully this helps someone else with a similar problem.

I found that you don't need to parse if you have a simple API setup with default format set to json, similar to below (in config/routes.rb):

 namespace :api, defaults: {format: :json}  do
    namespace :v1 do
      post "/controller_name" => 'controller_name#create'
      get "/controller_name" => 'controller_name#index'
    end
  end

The important thing I discovered is that the incoming post request comes is accessible by the variable request . In order to convert this into readable JSON format, you can call the following:

request.body.read()

如果您在params哈希中接收到JSON,则可以自己进行转换:

@var = JSON.parse(params[:name_of_the_JSON_fields])

Probably too late to help you, but perhaps future people will check here :) Perhaps rails is supposed to parse json for you, but that's never worked for me. I read the request body directly. I use the 'Yajl' json parser - it is very fast. But regular old 'json' will work here too (just use JSON.parse)

request.body.rewind
body = Yajl::Parser.parse request.body.read.html_safe

In most cases with the symptom desribed, the true root of the problem is the source of the incoming request: if it is sending JSON to your app, it should be sending a Content-Type header of application/json .

If you're able to modify the app sending the request, adjust that header, and Rails will parse the body as JSON, and everything will work as expected, with the parsed JSON fields appearing in your params hash.

When that is not possible (for instance when you don't control the source of the request - as in the case of receiving an Amazon SNS notification), Rails will not automatically parse the body as JSON for you, so the best you can to is read and parse it yourself, as in:

json_params = JSON.parse(request.raw_post)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM