views:

87

answers:

2

Say I would like to do something like this, is it possible?

require 'json'

class Person
attr_accessor :fname, :lname
end

p = Person.new
p.fname = "Mike"
p.lname = "Smith"

p.to_json
+3  A: 

Try it. If you're using Ruby on Rails (and the tags say you are), I think this exact code should work already, without requiring anything.

Rails supports JSON output from controllers, so it already pulls in all of the JSON serialization code that you will ever need. If you're planning to output this data through a controller, you might be able to save time by just writing

render :json => @person
Matchu
+1  A: 

Yes you can do it with to_json. Ref to_json

You need not to require json but gem json should be installed.

Salil