1. Dec 11th, 2007

    json_request: handling JSON request in Rails 2.0

    Here’s the easiest way to handle JSON requests in Rails 2.0:

    ./script/plugin install http://labnotes.org/svn/public/ruby/rails_plugins/json_request

    The plugin adds a MIME parser that parses requests with the content type application/json, and maps them to a request parameter using the controller name as guidance.

    class ItemsController < ApplicationController 
    
      def show
        respond_to do |format|
          format.json :json=>@item
          format.xml  :xml=>@item
        end
      end
    
      def update
        @item.update_attributes! params[:item]
        show
      end
    
    end

    It works the same way whether you feed it an XML document, JSON object, or URL-encoded parameters.

    Since the JSON object is not annotated, it figures out the parameter name based on the controller name, in this case ItemsController becomes item. If you prefer a different name, add this line to your controller:

    json_request :itemz

    The json_request method adds a filter and can take the only and except options, if you need to limit it to specific actions.

    1. Dec 13th, 2007

      Jon Crosby

      Clean implementation. Works perfectly. Thanks for putting this together and sharing it.

    2. Dec 17th, 2007

      Martin Gamsjaeger

      Hi,

      I just tried to POST nested JSON objects using your plugin and they seem to end up being an “Object” in rails parameter hash (…nested=%5Bobject%20Object%5D…), which makes them rather useless?

      I wanted to do this in order to POST to create and update in “the way rails form_for helpers do it” (something like sending a string representation of a nested hash, that gets parsed into a hash by rails).

      What I want to do is to POST plain JSON objects as parameters so that rails gets something like the following in its params hash.

      { :authenticity_token => ‘…’, :post => { :title => ‘…’, :body => ‘…’} }

      I think I could also get this to work using Form.serialize which I heard not only works for forms, but all other elements as well. However, this would require to put all my parameters into hidden inputs within a common container, whereas I could leave them where they are, if I could just POST nested JSON objects …

      Any ideas?

      PS: Other than that, thx for the great plugin! Works perfectly for not nested stuff for me.

    3. Dec 17th, 2007

      Assaf

      Martin, if you create a document that looks like this:

      { authenticity_token: ‘…’, post: { title: ‘…’, body: ‘…’} }

      and send it with the content type application/json, it will map nicely into a hash and made available from one of the request parameters.

      The plugin handles requests with content type application/json, the same way Rails already handles requests with content type application/xml. It will not magically parse JSON objects from inside an XML or a form (url-encoded) submission.

    4. Jan 17th, 2008

      Mathijs

      Hi,

      I’m trying your plugin with a RESTFUL rails application.
      I need to send an object to a resource-url in a PUT request.
      Using prototype’s method: ‘put’ won’t work since it just appends _method=put to the body, which isn’t good since the body should be all json.

      I tried sending { ‘_method’ : ‘put’, post: {…… } }(like your example above) but this also fails, RAILS gives error 405 (no POST allowed to this url), I guess rails checks the method before your plugin can kick in?

      Any thoughts?
      Thanks very much

    5. Jan 21st, 2008

      Assaf

      To send JSON requests using prototype.js, you’ll need something a bit more involved:

      Ajax.JSON = Class.create(Ajax.Request, {
      initialize: function($super, container, url, options) {
      options = options || {};
      options.contentType = ‘application/x-www-form-urlencoded’;
      options.postBody = Object.toJSON(options.object);
      $super(url, options);
      }
      });

      Which will let you do:

      new Ajax.Request(url, { object: myObject });

      (This code is untested, hopefully it will work as is)

    6. Feb 9th, 2008

      roger

      Works great with dojo too.

      Content type absolutely has to be ‘application/json’ or the rails server parses all the data as the key to a nil value.

    7. Mar 13th, 2008

      Seth Ladd

      Thanks very much for this plugin! Do you have an example of how to write a rspec or unit test when posting JSON? I’m trying to test POSTing of JSON, and I’m having a hard time getting the controller to understand I’m POSTing raw data like JSON.

      Thanks again!

    8. Mar 13th, 2008

      Seth Ladd

      Never mind, I figured it out by reading your plugin tests. Thanks very much!

    9. Mar 13th, 2008

      Semergence » Blog Archive » links for 2008-03-14

      [...] Labnotes » json_request: handling JSON request in Rails 2.0 (tags: rubyonrails json) [...]

    10. Apr 7th, 2008

      Todd Conley

      You’ll probably want to set both the content-type header and the accept header to json.

      curl -d “{ name: \”foo\”, count: 2 }” -H “Content-Type: application/json” -H “Accept: application/json” http://localhost:3000/items

      The content-type header is needed for the plug-in, and the accept header is for the respond_to/format.json block in your controller.

    11. May 16th, 2008

      Thomas Fee

      Thanks so much! It’s a shame Rails 2.0 doesn’t handle JSON properly out of the box.

    12. May 16th, 2008

      Thomas Fee

      But apparently, JSON support is going lately. This change-set mentions POST. I wonder if it covers PUT also. http://github.com/rails/rails/commit/4d594cffcfc93b37fad4e423ec8593299e50133c

    13. May 23rd, 2008

      KaBlog / Developer Release: GWT-REST

      [...] works out of the box with Rails 2.0 using JSON. I built it for Actionatr and extracted it to share with others who may be looking to do the same [...]

    14. May 25th, 2008

      DigitalHobbit » Blog Archive » Rails 2.1 and Incoming JSON Requests

      [...] Earlier this week, we tried to figure out the cleanest and easiest way to get our Rails app to accept incoming JSON requests. Up until recently, developers were able to use various Rails plugins for this purpose, such as the json_request plugin. [...]

    15. Aug 18th, 2008

      Higgaion

      hey, the plugin link is down. your xsl is broke?

    16. Aug 18th, 2008

      Assaf

      Thanks, fixed now.

    Your comment, here ⇓

    Or using OpenID