JavaScript: Reject non-finite numbers before JSON turns them into null
A failed calculation can produce NaN or Infinity. JSON serialization changes those numbers to null, which can make invalid measurements look like intentional missing values. A replacer can reject the primitive numbers encountered during serialization.
Set up
Tested on Debian 13 Linux with Node.js v24.19.0. Use Bash, Node.js on your PATH, a text editor, and the mktemp, rm and rmdir utilities. No packages or network access are needed. Keep the same terminal through cleanup. Stop if setup fails before saving the source.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as javascript-json-reject-nonfinite-values.mjs:
import assert from 'node:assert/strict';
function encodeMeasurements(value) {
return JSON.stringify(value, (key, item) => {
if (typeof item === 'number' && !Number.isFinite(item)) {
throw new TypeError(`Non-finite number at key ${JSON.stringify(key)}`);
}
return item;
});
}
console.log('Default:', JSON.stringify({ reading: NaN }));
for (const value of [NaN, Infinity, -Infinity]) {
assert.throws(() => encodeMeasurements({ reading: value }), TypeError);
assert.throws(() => encodeMeasurements([value]), TypeError);
assert.throws(() => encodeMeasurements(value), TypeError);
}
const encoded = encodeMeasurements({ readings: [0, 1.5, null] });
assert.equal(encoded, '{"readings":[0,1.5,null]}');
console.log('Accepted:', encoded);
console.log('Non-finite primitive numbers: rejected');Run:
node javascript-json-reject-nonfinite-values.mjsObserved output:
Default: {"reading":null}
Accepted: {"readings":[0,1.5,null]}
Non-finite primitive numbers: rejectedPreserve an explicit null
The JSON serialization specification calls a replacer before serializing a primitive number. Returning a finite number lets serialization continue; throwing stops it. An intentional null stays valid because its type is not number.
The checks include a number at the root, inside an object, and inside an array. The key in the error is only the current property name or index, not a full path. The root key is an empty string. Build path tracking separately if diagnostics need to identify a deeply nested field.
Keep the input contract narrow
Use this helper for plain measurement data with primitive numbers. It is not a full schema validator: it does not require fields, constrain ranges, reject omitted undefined properties, or handle cycles and BigInt values. Those retain their normal JSON behavior.
Objects with toJSON methods transform themselves before the replacer sees the result. Boxed number objects also need separate handling; this primitive-number check does not reject new Number(NaN). Validate incoming application data before encoding, and avoid treating successful serialization as proof that an arbitrary object is safe or complete. The helper only prevents the specific silent conversion shown here.
Clean up
Remove the saved file and empty scratch directory. If the directory is not empty, inspect its contents before removing anything else.
rm -- javascript-json-reject-nonfinite-values.mjs
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.