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?
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?
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}
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.