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.

JavascriptData Integrity

Code

javascriptsnippet
25 lines
// 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-value

How 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 early return when 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

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.