← 中文资源

简体中文版本

JSON.parse 对重复键取后值

重复键是合法 JSON 语法:JSON.parse 逐个赋值、后值覆盖前值,reviver 只会看到合并后的属性,被覆盖的前值拿不回来;要拦截重复得自己校验原文。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

各个操作都建立在顶层绑定之上: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