Monday, 17 September 2007

Dealing with JavaScript Object Notation (JSON)

Ruby on Rails provides an easy way to render JavaScript Object Notation (JSON) without actually having to deal with itty gritty details of forming the object literal.

# Controller
render :json => { :name => "Danny", :title => "Mr" }.to_json

produces

{ name: 'Danny', title: 'Mr' }

Once you have done so, you can create an object in javascript by running

var person = eval("(" + request.responseText) + ")");

You can then access the attributes by going person.name and person.title which returns "Danny" and "Mr", as expected.

No comments: