const order = { id: 1, items: ["áo"], createdAt: new Date("2026-11-14T03:00:00Z"), secret: undefined };
JSON.stringify(order);
// '{"id":1,"items":["áo"],"createdAt":"2026-11-14T03:00:00.000Z"}'
// undefined, hàm, symbol bị bỏ qua; Date tự gọi toJSON()
JSON.stringify(order, null, 2); // in đẹp, thụt 2 dấu cách
JSON.stringify(order, ["id", "items"]); // chỉ lấy các khóa này
JSON.stringify(order, (key, value) => (key === "id" ? undefined : value)); // replacerTự quy định cách serialize bằng toJSON:
class Money {
constructor(amount, currency) {
Object.assign(this, { amount, currency });
}
toJSON() {
return `${this.amount} ${this.currency}`;
}
}
JSON.stringifyWARNING
JSON.stringify ném lỗi với BigInt và với object có tham chiếu vòng. Map/Set thành {} — chuyển sang mảng/object trước.
const text = '{"name":"An","createdAt":"2026-11-14T03:00:00.000Z"}';
const data = JSON.parse(text, (key, value) =>
key === "createdAt" ? new Date(value) : value,
);
data.createdAt instanceof Date; // trueID từ hệ thống khác (Twitter/X, Snowflake ID, ngân hàng…) thường vượt Number.MAX_SAFE_INTEGER:
JSON.parse('{"id": 12345678901234567890}').id; // 12345678901234567000 — sai!Reviver cũ chỉ nhận giá trị đã bị chuyển sang number — quá muộn để sửa.
Reviver giờ nhận thêm tham số thứ ba context, trong đó context.source là đoạn văn bản gốc của giá trị nguyên thủy:
const data = JSON.parse(
'{"id": 12345678901234567890, "n": 1}',
(key, value, { source }) => (key === "id" ? BigInt(source) : value),
);
data.id; // 12345678901234567890n — chính xácChiều ngược lại: chèn nguyên văn một đoạn JSON vào kết quả stringify:
JSON.stringify(
{ id: 12345678901234567890n },
(key, value) => (typeof value === "bigint" ? JSON.rawJSON(value.toString()) : value),
);
// '{"id":12345678901234567890}'
JSON.stringify
JSON.rawJSON chỉ nhận văn bản của giá trị nguyên thủy JSON hợp lệ (số, chuỗi, true, false, null) — không nhận object hay mảng.
NOTE
Node 24 (sandbox của khóa) đã hỗ trợ cả context.source và JSON.rawJSON.
Comments