On this page

Why These Runtime Values Have No JSON Number Spelling
JSON excludes NaN, Infinity, and -Infinity as numbers because their spellings do not fit its number grammar. Holding one of these values in application memory does not give it a valid numeric representation in JSON text — and quoting the label creates a string, which requires an application agreement about its meaning.
The practical decision is what the receiver needs to know. An unavailable reading might become null under an agreed contract; another application might need to preserve each exceptional state through descriptive strings or tagged objects; a field that requires a permitted number may instead require rejection before transmission. Start by finding the original values and recording their locations, then inspect the proposed output and the receiver’s intended interpretation. The examples below are representation proposals and validation requirements awaiting execution in the intended environment — they do not establish the behavior of any particular serializer.
JSON numbers use decimal digits with an integer component and optional fraction or exponent components; spellings such as 12, -12.5, and 3E2 illustrate those forms. The grammar explicitly excludes the nonfinite values:
{"reading":NaN} // unpermitted token
{"reading":Infinity} // unpermitted token
{"reading":-Infinity} // the minus sign does not rescue it
{"reading":"Infinity"} // valid — but this is a STRING
In the quoted form, the value is a string whose spelling can serve an application convention, but quotation marks do not create a JSON number representing infinity — the receiving application must explicitly agree to interpret that string as an exceptional state. This distinction gives a useful first diagnostic question: is the problem an unpermitted numeric token, or a permitted string whose meaning the receiver has not agreed to accept? The remedies differ, and changing syntax can produce acceptable text while leaving the application contract unresolved.
Separate Parsing Errors from Serialization Choices
Trace three things separately: the value held by the application, the text prepared for transmission, and the value the receiver is expected to understand. Record the original state before choosing a conversion. For an application value containing NaN, consider these hypothetical serialization policies — design choices, not claims about a particular library:
| Proposed policy | Intended result | Consequence to inspect |
|---|---|---|
| Reject the value | Stop with a validation failure | Does the report identify the location? |
| Replace it with null | {"reading":null} |
Does the receiver accept the intended unavailable state? |
| Emit the unquoted label | {"reading":NaN} |
The text is outside JSON’s number grammar |
A rejection before output and an invalid token in transmitted text occur at different stages, and an error report should make that distinction clear so the developer knows whether to inspect input validation or the generated text. The null proposal illustrates a separate issue: even if the output passes a syntax check, the receiver cannot determine from null alone that the original value was NaN — the conversion has removed that distinction. For a concrete investigation, write down the application value, the exact emitted text, and the required receiver interpretation; an output satisfying only the middle step has not demonstrated that the exchange preserves the information the application needs.
// the three facts, held apart:
const appValue = NaN; // 1. memory
const emitted = JSON.stringify({reading: appValue}); // 2. text
emitted; // '{"reading":null}' — syntax ok, meaning destroyed
const receiverExpectation = 'must distinguish NaN from true null'; // 3. contract
// emitted satisfies #2 only — the exchange fails #3
Find Nonfinite Values and Report Their Paths
Design validation to inspect the original application values before any replacement occurs. Use a numeric classification operation whose behavior you have verified in the chosen language’s documentation, and confirm that it distinguishes NaN, positive infinity, and negative infinity from the finite numbers your contract accepts.
NaN values do not compare equal to themselves, so equality with NaN is unsuitable as the basis for identifying that state; that fact also does not supply a complete detector for the infinity cases — verify those explicitly:
// the verified classification, not the naive one:
Number.isNaN(v); // NaN only — v !== v is NOT the test to ship
v === Number.POSITIVE_INFINITY; // positive infinity, explicit
v === Number.NEGATIVE_INFINITY; // negative infinity, explicit
// three states, three distinct checks
Specify the walk before choosing an API. For an initial design limited to acyclic arrays and plain objects, use this language-neutral procedure:
- If the current value is numeric, apply the verified numeric check; record its path and exceptional state when appropriate.
- If it is an array, visit its elements and extend each path with the element index.
- If it is a plain object, visit its property values and extend their paths with the property names.
- Leave ordinary strings and other accepted values unchanged.
For simple property names, adopt paths such as metrics[1]; use $ as the reporting label when the entire input is an offending value. These are proposed reporting conventions — define additional notation before handling keys containing punctuation. Consider this application-value sketch, which is not JSON text:
{
metrics: [NaN, Infinity, -Infinity, 0],
note: "Infinity"
}
The acceptance requirements for the proposed validator:
| Input location | Required finding |
|---|---|
metrics[0] |
Report the NaN state |
metrics[1] |
Report positive infinity |
metrics[2] |
Report negative infinity |
metrics[3] |
No nonfinite finding |
note |
Preserve the ordinary string |
Also require a root NaN value to produce a finding at $, while a root string "NaN" remains ordinary text. These are cases to verify after implementation, not claimed results from an executed detector:
// the walk, language-neutral and shallow-first:
function findNonfinite(v, path = '$', out = []) {
if (typeof v === 'number') {
if (Number.isNaN(v)) out.push({path, state: 'NaN'});
else if (v === Number.POSITIVE_INFINITY) out.push({path, state: 'Infinity'});
else if (v === Number.NEGATIVE_INFINITY) out.push({path, state: '-Infinity'});
} else if (Array.isArray(v)) {
v.forEach((x, i) => findNonfinite(x, `${path}[${i}]`, out));
} else if (v && typeof v === 'object') {
for (const [k, x] of Object.entries(v)) findNonfinite(x, `${path}.${k}`, out);
}
return out; // strings like "Infinity" pass through untouched
}
Choose null When the Receiver Accepts an Unavailable Value
Choose null when the receiving contract explicitly permits it and assigns it a suitable meaning — for example, agreeing that an unavailable reading is represented as {"reading":null}. Confirm what unavailable means for this field: should the receiver omit the reading from a calculation, display an unavailable state, or request corrected input? Those are application decisions that acceptable JSON syntax cannot settle.
A single null replacement cannot retain the distinction among NaN, positive infinity, negative infinity, and a null already present in the input — once all four share the same representation, that field alone cannot reveal the original state. If those distinctions matter, consider companion status information:
{"reading":null,"status":"positive-infinity"}
The receiver must agree to both the extra field and the status vocabulary, and define a separate status for an original null if its origin must remain distinguishable. Review the complete mapping before adopting it: what would each exceptional state become, and what would an existing null become? If the answer deliberately combines states that the receiver treats identically, null may suit the contract; if the receiver needs different decisions for those states, retain the necessary information explicitly.
Choose Descriptive Strings When States Must Survive
Descriptive strings can preserve the three exceptional states when the receiver explicitly reserves and interprets those labels:
{"readings":["NaN","Infinity","-Infinity"]}
Under this agreement, "NaN" represents the original NaN state, "Infinity" positive infinity, and "-Infinity" negative infinity — meanings belonging to the proposed application contract, while the transmitted values are strings. This conversion changes the field’s type: confirm that the receiver permits these strings in the relevant positions and defines what happens when it encounters each one. A field described only as accepting numbers needs a revised agreement before this representation can be adopted.
Check whether the labels collide with ordinary text. Suppose the application already accepts the ordinary string "Infinity": converting a numeric infinity to the same string makes the two origins indistinguishable. Ask whether reserving that label would interfere with legitimate text. When the distinction matters, consider a tagged representation:
{"reading":{"kind":"nonfinite","label":"Infinity"}}
This is a proposed object shape requiring receiver agreement — define which labels it permits and how ordinary text is represented, and check whether existing application data could already use the same shape. A useful acceptance case places a converted infinity beside an original "Infinity" string and specifies how the receiver should distinguish them; if the representation cannot support a distinction the application requires, revise the contract before implementing the conversion:
// the collision case, stated as a test:
const payload = {a: {kind:'nonfinite', label:'Infinity'}, b: "Infinity"};
// the contract must say how a and b differ — or admit they don't
Reject Invalid Numeric States When the Contract Requires Numbers
Choose rejection when the field requires a permitted number and the contract accepts neither null nor an alternative representation. Detect the offending location before transmission so the caller can identify what needs correction. A proposed application flow: collect findings, stop preparation of the affected payload when findings exist, and return a structured validation result:
{"error":"nonfinite-number","path":"metrics[1]","state":"Infinity"}
The field names, error label, and wording above are application design choices — they do not describe a library exception or guarantee any serializer’s behavior. Decide whether the caller needs the first offending location or every location: for the earlier example, reporting all three paths could let the caller address the complete set in one correction. Keep the original values available during validation so an error can distinguish the states when useful.
Before relying on a serializer setting, check its approved documentation for nonfinite input handling, failure reporting, and whether it supplies locations — establish those details for the actual implementation instead of inferring them from an option name. Make rejection actionable: identify the path, state the field’s requirement, and explain which correction or agreed representation the caller may supply. A contract that requires numbers should not silently acquire a null or string conversion merely to produce output:
// the enforcement gate, before any serialization:
const findings = findNonfinite(payload);
if (findings.length) {
return {ok: false, errors: findings}; // stop here — no conversion "to help"
}
Keep Syntax, Numeric Range and Preserved Meaning Separate
Three checks answer different questions: does the text follow JSON syntax, can the receiver support the required numeric range and precision, and does the representation retain the meaning the application needs? 1E400 makes the distinction concrete: it is a permitted JSON number spelling, while its magnitude may create interoperability problems — JSON permits implementations to limit the range and precision of accepted numbers, so valid syntax does not establish that a particular receiver can retain the intended value. Investigate the receiver’s documented range handling separately from the invalid tokens NaN, Infinity, and -Infinity, and ask how values beyond its supported range are reported and what the application should do next:
// syntax-valid, receiver-limited:
JSON.parse('1E400'); // Infinity in JS — the parser "accepted" it
// but the value no longer survives as the decimal the sender wrote;
// range agreement is a separate contract question from syntax
| Proposed text value | Syntax category | Contract or receiver check |
|---|---|---|
12.5 |
Permitted number spelling | Does it satisfy the field’s requirements? |
NaN |
Unpermitted numeric token | Which conversion or rejection policy applies? |
Infinity |
Unpermitted numeric token | Must positive infinity remain distinguishable? |
-Infinity |
Unpermitted numeric token | Must negative infinity remain distinguishable? |
"Infinity" |
String | Is it ordinary text or an agreed reserved label? |
null |
Null | Was it original data or a replacement, and does that matter? |
1E400 |
Permitted number spelling | Can the receiver support the required magnitude? |
Build acceptance cases from this matrix: include finite input, all three nonfinite states, an existing null, an ordinary string matching a proposed label, and the large exponent example. For each case, specify the original value, intended output or validation failure, and required receiver interpretation — then verify those expectations in the implementation. Inspecting both the emitted text and the receiving result makes changes in syntax and changes in meaning visible. Paste each proposed output into the JSON Inspector on this site: the strict parser flags the unpermitted tokens immediately, the raw pane shows exactly which labels carry quotes, and the whole matrix runs locally in one paste.