Canonical JSON Strings For Stable Cache Keys
Insertion-order keys make equal objects serialize differently; recursively sorting keys before JSON.stringify yields one canonical string per value.
Code
// JSON.stringify walks keys in insertion order, so equal objects can
// serialize differently and get different cache keys or signatures.
const a = { user: 'ada', role: 'admin' };
const b = { role: 'admin', user: 'ada' };
console.log('raw equal:', JSON.stringify(a) === JSON.stringify(b));
// Recursively sort keys to make serialization canonical.
function canonicalJSON(value) {
if (Array.isArray(value)) return value.map(canonicalJSON);
if (value && typeof value === 'object') {
return Object.fromEntries(
Object.keys(value).sort().map((key) => [key, canonicalJSON(value[key])])
);
}
return value;
}
const canonical = (obj) => JSON.stringify(canonicalJSON(obj));
console.log('canonical equal:', canonical(a) === canonical(b));
console.log('canonical a:', canonical(a));
// Same input always yields the same string, order-independent.
const cache = new Map();
cache.set(canonical(a), 'expensive-computed-value');
console.log('cache hit:', cache.get(canonical(b)));Output
Captured from a sandboxed run of this snippet in the build pipeline.
raw equal: false
canonical equal: true
canonical a: {"role":"admin","user":"ada"}
cache hit: expensive-computed-valueHow it works
Canonical JSON Strings For Stable Cache Keys comes down to the functions canonical and canonicalJSON.
What to watch for
- The whole dependency story is the language version itself.
- The guard
value && typeof value === 'object'short-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
The main signature reads const canonical = (obj)
The file announces its steps in the output: raw equal:, canonical equal:, canonical a:.
Statements that matter
const canonical = (obj) => JSON.stringify(canonicalJSON(obj));
Object.keys(value).sort().map((key) => [key, canonicalJSON(value[key])])
);
if (Array.isArray(value)) return value.map(canonicalJSON);
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.Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `canonical`, `canonicalJSON` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.