This project is archived and is in readonly mode.

#2753 ✓resolved
Cody Fauser

#to_json behavior still different between Rails 2.3.2.1 and Rails 2-3-stable

Reported by Cody Fauser | June 3rd, 2009 @ 04:17 PM | in 2.3.3

Ticket #2690 helped the problems with to_json serialization in the Rails 2.3 branch, but the behavior of to_json is still different between Rails 2.3.2.1 and Rails 2.3-stable. The following example illustrates the problem:

class A
  def initialize
    @a, @b = 1, 2
  end
  
  def to_json(options = {})
    @a.to_json(options)
  end
end

class B
  def initialize
    @a = A.new
  end
end

In Rails 2.3.2.1 the output is the following:

b = B.new
b.to_json #=> {"a": 1}

In Rails 2.3-stable the output is:

b = B.new
b.to_json #=> {"a":{"a":1,"b":2}}

The problem is caused by ActiveSupport::JSON.encode calling rails_to_json instead of to_json on the objects. Overridden to_json() methods child objects are never called.

Going forward all objects will have to have a rails_to_json() method, but the problem is that this functionality changed in the stable 2-3 branch.

In Shopify we have monkey patched active_support/json/encoding.rb to call value.to_json() instead of value.rails_to_json() to achieve the same output from Rails 2.3.2.1.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Referenced by

Pages