json.stringify() 遇到对象时优先调用其 tojson() 方法(若存在),用其返回值参与序列化;tojson 必须返回可序列化值,可实现字段过滤、重命名、格式转换及嵌套递归控制。

在 JavaScript 中,JSON.stringify() 遇到对象时会默认调用其 toJSON() 方法(如果存在),并用该方法的返回值参与序列化。通过自定义 toJSON,你可以完全决定这个对象“对外呈现”的结构,而不是暴露原始属性或内部状态。
toJSON 方法的基本规则
toJSON 是一个普通函数,必须返回一个可被 JSON 序列化的值(即:字符串、数字、布尔值、null、数组、或另一个拥有 toJSON 的对象)。它不会改变原对象,只影响序列化结果。
- 函数名必须严格为
toJSON(大小写敏感) - 它会在
JSON.stringify()内部自动触发,无需手动调用 - 如果返回
undefined,该字段会被忽略(整个键值对不出现) - 如果返回其他不可序列化类型(如
Date、Function、undefined),会报错或被转为null(取决于上下文)
按需过滤与重命名字段
常见场景是隐藏敏感字段(如 _id、passwordHash)或统一输出格式(如把 createdAt 转为 ISO 字符串)。
例如:
const user = {
id: 123,
_internalId: 'abc-456',
name: 'Alice',
passwordHash: 'sha256...',
createdAt: new Date('2023-01-01'),
toJSON() {
return {
userId: this.id,
fullName: this.name,
registeredAt: this.createdAt.toISOString()
// _internalId 和 passwordHash 被主动排除
};
}
};
JSON.stringify(user);
// → {"userId":123,"fullName":"Alice","registeredAt":"2023-01-01T00:00:00.000Z"}
支持嵌套对象与递归控制
toJSON 不仅适用于顶层对象,也适用于任意嵌套层级的对象。只要子对象定义了 toJSON,它就会被递归调用。
- 适合封装业务模型类(如
User、Order) - 避免在每个
JSON.stringify()调用前手动映射 - 保持数据结构与序列化逻辑解耦
示例中,若 user.profile 也是一个带 toJSON 的对象,它会自动按自己的规则输出,无需外层干预。
配合 class 使用更清晰
使用 ES6 class 定义模型时,toJSON 更易维护和复用:
class Product {
constructor(id, title, price, stock) {
this.id = id;
this.title = title;
this.price = price;
this.stock = stock;
this._updatedAt = new Date();
}
toJSON() {
return {
productId: this.id,
name: this.title,
price: Number(this.price.toFixed(2)),
inStock: this.stock > 0,
lastUpdated: this._updatedAt.toISOString()
};
}
}
const p = new Product(789, 'Wireless Mouse', 29.99, 42);
JSON.stringify(p);
// → {"productId":789,"name":"Wireless Mouse","price":29.99,"inStock":true,"lastUpdated":"..."}
这样既保证实例行为一致,又让 API 响应格式稳定可控。











