用两个简短示例看清 Date.toJSON() 与 replacer 的调用顺序,并演示怎样显式保留日期类型信息。
JSON.stringify() 序列化 Date 时,为什么 replacer 收到的是字符串?
时间:2026-12-01
浏览:234
文章目录
给报表里的日期加类型标记时,很容易在 replacer 里直接写 value instanceof Date。但这个判断对普通的日期字段不会命中。JSON.stringify() 先调用 Date 的 toJSON(),再把返回值交给 replacer。有效日期到这一步已经是 ISO 字符串。
同一属性为何呈现两种类型?
用一个固定的 UTC 时间看看两边的值。第一行日志检查 replacer 收到的 value,第二行回到原对象上读取 createdAt。
{
const report = { createdAt: new Date('2025-01-02T03:04:05.000Z') };
const json = JSON.stringify(report, function (key, value) {
if (key === 'createdAt') {
console.log('replacer:', typeof value, value instanceof Date);
console.log('original:', this[key] instanceof Date);
}
return value;
});
console.log(json);
}

第一行的 string false 说的是回调参数,第二行的 true 说的是原属性。这个例子里,toJSON() 返回了一个用于序列化的字符串,报表里的 createdAt 仍然存着 Date 对象。
这里写的是普通函数。JSON.stringify() 会把持有当前属性的对象设为回调的 this,箭头函数不会接收这个绑定。用 this[key] 排查普通属性很方便。遇到 getter 时,这会重新取值。自定义 toJSON() 也可能在回调之前改掉属性。

createdAt 时的调用顺序。导出时把日期和普通字符串分开
如果日期序列化出来的字符串和备注完全一样,JSON.parse() 会把两者都读成字符串。下面在导出时给 createdAt 加上 kind 和 iso,让读取方知道哪个值要还原成日期。
{
const report = { createdAt: new Date('2025-01-02T03:04:05.000Z') };
const wireReport = {
createdAt: { kind: 'date', iso: report.createdAt.toISOString() },
note: '2025-01-02T03:04:05.000Z',
};
const saved = JSON.parse(JSON.stringify(wireReport));
console.log('kind:', saved.createdAt.kind);
console.log('iso:', saved.createdAt.iso);
const restored = new Date(saved.createdAt.iso);
console.log('same instant:', restored.getTime() === report.createdAt.getTime());
console.log('note type:', typeof saved.note);
}

示例读回自己刚写出的数据,只还原 createdAt.iso。两边的时间戳相等。note 的内容和日期字符串完全一样,仍然按文本保留。处理外部文件时,先校验字段结构、类型标记和日期值,再按约定还原。
无效日期会在哪里报错?
无效日期对象(例如 new Date(NaN))使用内置的 toJSON() 时会返回 null,默认序列化也就写出 null。第二段代码显式调用 toISOString(),这里遇到无效日期会抛出 RangeError。导出格式允许空值时,可以在构造 wireReport 时决定怎样表示缺失值。
实用工具推荐
绿化、压缩、噪点和虚拟水印,自由调节做旧程度。
选择画质和输出格式,预览压缩前后的大小。