I need convert a Ruby hash which contains some BigDecimal fields into JSON.
I need the BigDecimal to be converted into Float/Integer, but the 'json' lib always convert it into the scientific notation.
require 'json'
require 'bigdecimal'
obj = {}
obj['created_at'] = BigDecimal('0.12345')
puts "JSON.dump(obj) = #{JSON.dump(obj)}"
puts "JSON.generate(obj) = #{JSON.generate(obj)}"
puts "JSON.fast_generate(obj) = #{JSON.fast_generate(obj)}"
puts "JSON.pretty_generate(obj) = #{JSON.pretty_generate(obj)}"
Results:
JSON.dump(obj) = {"created_at":"0.12345e0"}
JSON.generate(obj) = {"created_at":"0.12345e0"}
JSON.fast_generate(obj) = {"created_at":"0.12345e0"}
JSON.pretty_generate(obj) = {
"created_at": "0.12345e0"
}
Is there any JSON lib that can specify the number format so when i parsing an object, the BigDecimal field won't be converted into the scientific notation?
obj['created_at'] = BigDecimal.new('0.12345')
JSON.parse(obj) = { "created_at": "0.12345" } # not 0.12345e0
I'm using ruby 2.4.1p111