BigDecimal encoded differently in compat mode #64

Closed
wants to merge 1 commit into
from

Projects

None yet

2 participants

In compat mode, BigDecimals are encoded as strings. In other modes, they are numbers. This is probably a mistake, because the correct code appears to be accidenatlly commented out in 7a573f2.

This PR reverts it and fixes the problem.

Oj.dump(BigDecimal.new("7"), mode: :strict)
=> 0.7E1
Oj.dump(BigDecimal.new("7"), mode: :object)
=> 0.7E1
Oj.dump(BigDecimal.new("7"), mode: :compat)
=> "0.7E1"
Owner
ohler55 commented Feb 6, 2013

The code is correct as it is. Compat mode is meant to be compatible with other parsers and sadly they do not handle larger numbers. This use of strings was done in a fairly recent release due to complaints that it broke other parsers. If you have a good use case where the value should be a number instead of a string I can consider other options for supporting both opinions.

Thanks for your answer. I didn't expect the behaviour was intentional.

I have some BigDecimals that come from an outside source and I want to serialise them as JS numbers, not strings. Also, I want to use MultiJson which pretty much forces me to use compat mode (possibly a good thing). I thought fixing the behaviour of compat mode with respect to BigDecimals was the way to go.

As I understand it isn't really, so now that I'm trying to override this behaviour, I'm trying to use to_json instead:

class BigDecimal
  def to_json
    "foo"
  end
end

Oj.dump(BigDecimal.new("7"), mode: :compat)
# => "0.7E1"

Does to_json not get called for BigDecimals?

Owner
ohler55 commented Feb 6, 2013

I could add an option to output BigNumbers as either digits or a string. Would that work for you.

You are right, BigNumbers are handled differently since under the covers in most Ruby implementations they are not regular objects but rather special data structures. Oj should check for to_json() in compat mode. I will mark that as a bug and get it fixed in a future release.

An option would definitely work -- a call to to_json would also be sufficient in my particular situation. Either works for me. Thanks for your swift responses. I appreciate your work on Oj!

Owner
ohler55 commented Feb 6, 2013

Thanks. I will do both.

@sferik sferik referenced this pull request in intridea/multi_json Feb 10, 2013
Closed

Inconsistant serialization of BigDecimal instances #80

@ohler55 ohler55 closed this Feb 11, 2013
Owner
ohler55 commented Feb 11, 2013

I create 2 issues to to track the feature requests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment