json icon indicating copy to clipboard operation
json copied to clipboard

`JSON.generate` ignores `to_json` method inside Fixnum or Bignum

Open sproot opened this issue 9 years ago • 1 comments

Here is an example:

> (1..4).to_json
=> "[\"1..4\"]" 
> JSON.generate [1..4]
=> "[\"1..4\"]" 
class Range
  def to_json(*a)
    {
      'json_class'   => self.class.name, # = 'Range'
      'data'         => [ first, last, exclude_end? ]
    }.to_json(*a)
  end
end
> (1..4).to_json
=> "{\"json_class\":\"Range\",\"data\":[1,4,false]}" 
> JSON.generate [1..4]
=> "[{\"json_class\":\"Range\",\"data\":[1,4,false]}]" 

So to_json works well with Range class. But let's try it with Fixnum

1.to_json
=> "1" 
>  JSON.generate [1]
=> "[1]" 
class Fixnum
  def to_json(*a)
    { value: self.to_s }.to_json(*a)
  end
end
> 1.to_json
=> "{\"value\":\"1\"}" 
>  JSON.generate [1]
=> "[1]" 

WAT? Why do we have different behaviour for integers? :(

sproot avatar Aug 12 '15 13:08 sproot

I confirm that this bug is still present. It affects the C implementation, but not json/pure. This is due to an optimization that should check if the builtin method has been redefined or not. (did not check Java port)

marcandre avatar Jun 30 '20 07:06 marcandre