JSON nâng cao: reviver, toJSON và JSON.parse source text (ES2026)
JSON.stringify
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.stringify({ price: new Money(150000, "VND") }); // '{"price":"150000 VND"}'WARNING
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.
JSON.parse và reviver
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; // trueVấn đề: số lớn bị mất chính xác
ID 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.
JSON.parse source text access — ES2026
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ácJSON.rawJSON — ES2026
Chiề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({ price: 1.10 }); // '{"price":1.1}'
JSON.stringify({ price: JSON.rawJSON("1.10") }); // '{"price":1.10}' — giữ đúng định dạng
JSON.isRawJSON(JSON.rawJSON("1")); // trueJSON.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