Ruby on Rails
HowtoGenerateJSON

Update: If you want to obtain all columns(contains id field), use columns instead content_columns.

Update: Rails 2 has mature JSON serialization support. You can read more at http://blog.codefront.net/2007/10/10/new-on-edge-rails-json-serialization-of-activerecord-objects-reaches-maturity/.

Update: I just tested the first example below with Rails 1.1.2. It seems Rails now has JSON support built in. No need for installing the ruby gem or the line “require ‘json/objects’”.

For AJAX driven pages, JSON can come in handy – you can return send JavaScript objects directly from your actions.

Installing

You can find a JSON implementation for Ruby here at SourceForge. There is also a gem, so gem install ruby-json is the easy way to install it.

Rendering JSON in actions

Sending JSON is almost trivial:

require 'json/objects'

def MyController < ApplicationController
  def give_me_json
    # make sure not to send html but text/plain
    @headers["Content-Type"] = "text/plain; charset=utf-8"

    data = { :foo => 'bar', :etc => 'rez' }
    render :text => data.to_json
  end
end

ActiveRecords to JSON

This snippet will come in handy when you want to send ActiveRecord objects via model.to_json

require 'json/objects'

class ActiveRecord::Base
  # Converts the ActiveRecord object to a JSON string. Only columns with simple
  # types are included in this object so no recursion problems can occur.
  def to_json
    result = Hash.new
    
  #  self.class.columns.each do |column|
  #    result[column.name.to_sym] = self.send(column.name)
  #  end

    self.class.content_columns.each do |column|
      result[column.name.to_sym] = self.send(column.name)
    end
    
    result.to_json
  end
end

Note: If you plan to uncomment and use the self.class.columns block instead of the self.class.content_columns you should probably use…

self.class.content_columns.each do |column|
   if self.attributes.include?(column.name)
    result[column.name.to_sym] = self.send(column.name)
   end
end

… so that the serialization will not error even if your model object does not have the full complement of attributes (eg. you did a find() with a :select option that only retrieved a subset of columns).

Using JSON for Firefox search plugin suggests

I found an article on how to write a Firefox search plugin with suggests using JSON