JSON.parse Lets Duplicate Keys Collapse

Duplicate JSON keys are legal syntax; JSON.parse keeps the last assignment and the reviver only sees merged properties, so overwritten values are unrecoverable.

JavascriptData Integrity

Code

javascriptsnippet
14 lines
// JSON syntax allows duplicate keys; JSON.parse assigns them in order, so the later value wins
const parsed = JSON.parse('{"region": "eu", "region": "us"}');
console.log('last wins:', parsed.region);
console.log('own keys:', Object.keys(parsed).length);

// the reviver only sees the merged property: 'a' appears once and the earlier value 1 is already gone
const calls = [];
JSON.parse('{"a": 1, "b": 2, "a": 3}', (key, value) => {
  if (key !== '') calls.push(`${key}=${value}`);
  return value;
});
console.log('reviver calls:', calls.join(' '));

// rejecting duplicate keys requires re-checking the raw text; the standard library has no hook like Python's object_pairs_hook

Output

Captured from a sandboxed run of this snippet in the build pipeline.

last wins: us
own keys: 1
reviver calls: a=3 b=2

How it works

The file’s state is a handful of top-level bindings: parsed, calls.

Watch out for

  • No package installation, no environment variables, no setup steps.

Using it

The demo output is labeled (last wins:, own keys:, reviver calls:), so every line of output points back to the operation that emitted it.

Key statements

JSON.parse('{"a": 1, "b": 2, "a": 3}', (key, value) => {
  if (key !== '') calls.push(`${key}=${value}`);
  return value;
});

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. Its state lives in module-level bindings: `parsed`, `calls`.