views:

824

answers:

5

Is there an easy way to return data to web service clients in JSON using Rails?

+1  A: 

Rails monkeypatches most things you'd care about to have a #to_json method.

Off the top of my head, you can do it for hashes, arrays, and ActiveRecord objects, which should cover about 95% of the use cases you might want. If you have your own custom objects, it's trivial to write your own to_json method for them, which can just jam data into a hash and then return the jsonized hash.

Orion Edwards
monkeypatches? I have no idea what that means, but I could guess it refers to providing that method to most, if not all, objects
Adrian Anttila
It's patching an existing object, adding the method or changing it if it exists. It's really just dynamic language extension.
The Wicked Flea
+1  A: 

There is a plugin that does just this, http://blog.labnotes.org/2007/12/11/json_request-handling-json-request-in-rails-20/

And from what I understand this functionality is already in Rails. But go see that blog post, there are code examples and explanations.

Evgeny
+4  A: 

Rails resource gives a RESTful interface for your model. Let's see.

Model

class Contact < ActiveRecord::Base
  ...
end

Routes

map.resources :contacts

Controller

class ContactsController < ApplicationController
  ...
  def show
    @contact = Contact.find(params[:id]

    respond_to do |format|
      format.html 
      format.xml {render :xml => @contact}
      format.js  {render :json => @contact.json}
    end
  end
  ...
end

So this gives you an API interfaces without the need to define special methods to get the type of respond required

Eg.

/contacts/1 # Responds with regular html page

/contacts/1.xml # Responds with xml output of Contact.find(1) and its attributes

/contacts/1.js # Responds with json output of Contact.find(1) and its attributes
JasonOng
A: 

ActiveRecord also provides methods to interact with JSON. To create JSON out of an AR object, just call object.to_json. TO create an AR object out of JSON you should be able to create a new AR object and then call object.from_json.. as far as I understood, but this did not work for me.

Nils