实现说明
各个操作都建立在顶层绑定之上:parsed、calls。
使用要点
- 直接运行文件,输出会带上标签,比如
last wins:、own keys:、reviver calls:——输出的每一行都能指回产生它的那次调用。
常见问题
运行之前需要装什么吗?
不需要——用到的每个 API 都随语言运行时自带,无需安装。 文件的状态由几个模块级绑定持有:parsed、calls。
核心语句
JSON.parse('{"a": 1, "b": 2, "a": 3}', (key, value) => {
if (key !== '') calls.push(`${key}=${value}`);
return value;
});
代码示例
// 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