You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何JSON.stringify替换器参数两种写法结果截然不同?

JSON.stringify替换器参数的差异原因解析

先看两段代码的执行结果差异:

第一段代码(过滤string类型值):

const person = {
  id: 1,
  firstName: 'Jack',
  lastName: 'White',
  age: 25,
};

const json = JSON.stringify(person, (key, value) => typeof(value) == "string" ? undefined : value);

console.log(json); // 输出: {"id":1,"age":25}

第二段代码(过滤非number类型值):

const person = {
  id: 1,
  firstName: 'Jack',
  lastName: 'White',
  age: 25,
};

const json = JSON.stringify(person, (key, value) => typeof(value) == "number" ? value : undefined);

console.log(json); // 输出: undefined

差异核心原因

问题出在JSON.stringify替换器的执行顺序:替换器会先对整个要序列化的对象执行一次调用,此时key是空字符串,value就是完整的person对象(typeof为object)。

  • 第一段代码中,判断typeof value == "string"不成立,直接返回原对象,后续才会逐个遍历对象属性,过滤掉string类型的属性值,最终得到保留number属性的JSON。
  • 第二段代码中,判断typeof value == "number"不成立,直接返回undefined,这会让JSON.stringify直接忽略整个对象,所以最终输出undefined。

如果要让第二段代码达到预期效果,只需给替换器加个顶层对象的判断逻辑:

const json = JSON.stringify(person, (key, value) => {
  // 顶层对象(key为空)直接返回,不做过滤
  if (key === '') return value;
  return typeof(value) == "number" ? value : undefined;
});
console.log(json); // 输出: {"id":1,"age":25}

内容的提问来源于stack exchange,提问作者SpikeSpike_96

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:15:44