json
json copied to clipboard
Dumping and parsing BigDecimal in scientific notation
It looks like JSON has no problem parsing scientific notation however it can't produce it, instead string is produced. In my case I work with BigDecimals mostly and I need to pass encoded JSON data from one node to another to continue computation on the other node. Sorry if I'm not aware if solution exists, but could been able to find one. Maybe related to #219
decimal = (BigDecimal('1') / BigDecimal('3')) # 0.333333333333333333e0
hash = { 'bc' => decimal } # {"bc"=>0.333333333333333333e0}
JSON(JSON(hash)) == hash # false
JSON(JSON(hash)) # {"bc"=>"0.333333333333333333e0"}
JSON(JSON(decimal)) == decimal # => false
JSON(JSON(decimal)) # => "0.333333333333333333e0"
UPD. I figured out that I can control to some degree how scientific notation is parsed, but didn't found a way to control how to dump it.
puts JSON.dump(hash) # {"bc":"0.333333333333333333e0"}
JSON.parse('{"bc":"0.333333333333333333e0"}', decimal_class: BigDecimal) # {"bc"=>"0.333333333333333333e0"}
JSON.parse('{"bc":0.333333333333333333e0}', decimal_class: BigDecimal) # {"bc"=>0.333333333333333333e0}
JSON.parse('{"bc":0.333333333333333333e0}') # {"bc"=>0.3333333333333333}
JSON.parse('{"bc":"0.333333333333333333e0"}') # {"bc"=>"0.333333333333333333e0"}