0

The common knowledge of NaN and Infinity serialization in JSON via JavaScript is simple:

JSON.stringify({ x: NaN });
"{"x":null}"

JSON.stringify({ x: Infinity });
"{"x":null}"

The question is what behind this strange decision?

shadeglare
  • 7,006
  • 7
  • 47
  • 59

2 Answers2

2

I can't tell you the reason behind the decision, but here's one possible way to deal with it:

const obj = {foo: NaN, bar: Infinity, baz: 42}
JSON.stringify(obj, (name, val) => typeof(val) === 'number' && (isNaN(val) || !isFinite(val)) ? val.toString() : val)

The output is:

{"foo":"NaN","bar":"Infinity","baz":42}

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
kshetline
  • 12,547
  • 4
  • 37
  • 73
  • It looks like they started out trying to come up with a standard that didn't assume any particular implementation at either end, hence leaving things that are not universally supported, such as NaN or Inf. Then in the very next paragraph it acknowledges that IEEE 754 is (in practise) pretty much everywhere... IMHO It would probably have been better to include things like NaN, Inf, and then leave it up to those very few implementations that don't have them to work out how to deal with them, if encountered. ASN.1, which also generally encodes floats in a text format, does have NaN, +/-Inf – bazza Jul 21 '19 at 06:34
  • Interestingly, ASN.1 can use JSON as a wireformat these days. The standards seem to be a bit hazy as to what ASN.1 should do with NaN, +/-Inf if encoding to JSON. Sorry, this is a bit of a rabbit hole, but I find it intersting to compare design decisions. – bazza Jul 21 '19 at 06:59
  • 1
    There's also this: https://github.com/json5/json5, which takes care of a few annoying limitations of JSON. I've noticed a few JSON parsers already have some of the extra leniency provided here, like allowing inline comments in JSON. One extra proposal I'd make is allowing a trailing 'n' at the end of numbers to support `BigInt`. – kshetline Jul 21 '19 at 11:43
  • That looks quite good and sensible. It'd be nice if the IETF took that up. – bazza Jul 21 '19 at 21:22
2

Per RFC 7159 - The JavaScript Object Notation (JSON) Data Interchange Format

Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.

I would speculate that this is because NaN and Infinity don't actually represent numbers and/or can't be represented by any type of numeric format.

Community
  • 1
  • 1
Erik Philips
  • 53,428
  • 11
  • 128
  • 150