JSON Canonicalizer For Stable Signing
Serialize JSON with sorted keys, strict numeric checks and cycle rejection so independent services compute identical signing payloads.
Code
export function canonicalizeJson(value: unknown): string {
return serialize(value, new Set<object>());
}
function serialize(value: unknown, stack: Set<object>): string {
if (value === null) return "null";
const type = typeof value;
if (type === "string") return JSON.stringify(value) as string;
if (type === "boolean") return value ? "true" : "false";
if (type === "number") {
if (!Number.isFinite(value)) throw new TypeError("non-finite numbers are not allowed");
return JSON.stringify(value) as string;
}
if (type === "undefined" || type === "function" || type === "symbol" || type === "bigint") {
throw new TypeError("value of type " + type + " is not valid JSON");
}
if (Array.isArray(value)) {
if (stack.has(value)) throw new TypeError("cyclic array");
stack.add(value);
const items = value.map((item) => serialize(item, stack));
stack.delete(value);
return "[" + items.join(",") + "]";
}
if (type === "object") {
const object = value as Record<string, unknown>;
const prototype = Object.getPrototypeOf(object);
if (prototype !== Object.prototype && prototype !== null) {
throw new TypeError("only plain objects can be canonicalized");
}
if (stack.has(object)) throw new TypeError("cyclic object");
stack.add(object);
const keys = Object.keys(object).sort();
const parts = keys.map((key) =>
(JSON.stringify(key) as string) + ":" + serialize(object[key], stack));
stack.delete(object);
return "{" + parts.join(",") + "}";
}
throw new TypeError("unsupported value");
}How it works
The working surface is the functions canonicalizeJson and serialize — everything else is wiring.
Invalid states are rejected up front: it throws TypeError instead of continuing with bad data.
What to watch for
- The guard
value === nullshort-circuits the flow with an earlyreturnwhen its condition holds.
Using it
The main signature reads export function canonicalizeJson(value: unknown)
canonicalizeJson is what another module would consume; nothing else here is load-bearing for callers.
Key statements
if (type === "string") return JSON.stringify(value) as string;
return serialize(value, new Set<object>());
if (!Number.isFinite(value)) throw new TypeError("non-finite numbers are not allowed");
Interactive Tools for This Topic
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON Diff ViewerCompare two JSON documents and list every added, removed, and changed path in a structural diff, with clear before and after values.
FAQ
- Does the code validate its input?
- It throws `TypeError` before any real work runs, via the guard `value === null` — handle it at the call site or let it propagate deliberately.
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free. The file defines `canonicalizeJson`, `serialize` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.