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

若如初见. 提交于 2019-12-03 09:52:11

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()

If you are receiving JSON in the params hash you can convert it yourself:

@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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!