Temporal.PlainYearMonth.prototype.toJSON()
toJSON() 方法是 Temporal.PlainYearMonth 例項的方法,它會返回一個字串,表示該年月,格式與呼叫 toString() 方法的 RFC 9557 格式相同。它旨在被 JSON.stringify() 隱式呼叫。
語法
js
toJSON()
引數
無。
返回值
一個字串,表示給定日期,採用 RFC 9557 格式,如果日曆註解不是 "iso8601",則會包含日曆註解。
描述
當 Temporal.PlainYearMonth 物件被序列化為字串時,toJSON() 方法會被 JSON.stringify() 自動呼叫。此方法通常旨在預設情況下有效地序列化 Temporal.PlainYearMonth 物件,以便後續可以使用 Temporal.PlainYearMonth.from() 函式作為 JSON.parse() 的 reviver 來反序列化。
示例
使用 toJSON()
js
const ym = Temporal.PlainYearMonth.from({ year: 2021, month: 8 });
const ymStr = ym.toJSON(); // '2021-08'
const ym2 = Temporal.PlainYearMonth.from(ymStr);
JSON 序列化和解析
此示例展示瞭如何在不進行額外操作的情況下將 Temporal.PlainYearMonth 序列化為 JSON,以及如何將其解析回原樣。
js
const ym = Temporal.PlainYearMonth.from({ year: 2021, month: 8 });
const ymStr = JSON.stringify({ event: ym }); // '{"event":"2021-08"}'
const obj = JSON.parse(ymStr, (key, value) => {
if (key === "event") {
return Temporal.PlainYearMonth.from(value);
}
return value;
});
規範
| 規範 |
|---|
| Temporal # sec-temporal.plainyearmonth.prototype.tojson |
瀏覽器相容性
載入中…