The JSON specification states:
Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.
However Float#to_json
simply calls to_s
which does emit these values. js handles this by emitting "null" instead. Some other engines handle it by emitting zero for NaN, or very high (or low) numbers for infinity. Some engines break the specification by emitting Infinity
, -Infinity
and NaN
. Go handles it by raising.
What should crystal do?
I just checked what Ruby does and it raises. Raising is probably a good idea.
Unfortunately it's quite an annoying reaction: one accidental Infinity or NaN and your program (well, fiber) crashes. It's probably the correct reaction though.
But using an arbitrary replacement is probably worse: you get incorrect data on the other side...
I don't think NaN/Infinity are that common for that to be a common error to happen (I never saw that exception in my life and I've been programming in Ruby, using JSON, for several years now)
Most helpful comment
But using an arbitrary replacement is probably worse: you get incorrect data on the other side...
I don't think NaN/Infinity are that common for that to be a common error to happen (I never saw that exception in my life and I've been programming in Ruby, using JSON, for several years now)