to_json and as_json

If you want to change the root; for example modify the classname when calling to_json on an AR model.

i.e.

Book.first.to_json
 #=> "{\"book\":{\"created_at\":\"2010-03-23 

Book.first.to_json(:root => 'libro')
 #=> "{\"libro\":{\"created_at\":\"2010-03-23 

Note that :root is not available before Rails 3.0.5

To be compatible with Rails 3, override as_json instead of to_json. It was introduced in 2.3.3:

def as_json(options={})
  { :libro => { :created_at => created_at } }
end

Make sure ActiveRecord::Base.include_root_in_json = false. When you call to_json, behind the scenes as_json is used to build the data structure, and ActiveSupport::json.encode is used to encode the data into a JSON string.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s