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.
Code
// 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_hookOutput
Captured from a sandboxed run of this snippet in the build pipeline.
last wins: us
own keys: 1
reviver calls: a=3 b=2How 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
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.Duplicate Line RemoverFind unique, duplicate, or counted lines with optional case sensitivity and whitespace trimming, all processed locally in the browser.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.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.