Temporal.Instant.prototype.toJSON()
toJSON() 方法是 Temporal.Instant 例項的一個方法,它返回一個字串,該字串表示此 instant 的格式與呼叫 toString() 相同,都是 RFC 9557 格式。它 intended to be implicitly called by JSON.stringify()。
語法
js
toJSON()
引數
無。
返回值
返回一個字串,該字串表示給定的 instant,格式為 RFC 9557 格式,具有表示持續時間所需的精度,並帶有 UTC 時區指示符 Z。
描述
當 Temporal.Instant 物件被字串化時,toJSON() 方法會被 JSON.stringify() 自動呼叫。此方法通常 intended to, by default, usefully serialize Temporal.Instant objects during JSON serialization,然後可以使用 Temporal.Instant.from() 函式作為 JSON.parse() 的 reviver 來反序列化。
示例
使用 toJSON()
js
const instant = Temporal.Instant.fromEpochMilliseconds(1627821296000);
const instantStr = instant.toJSON(); // '2021-08-01T12:34:56Z'
const i2 = Temporal.Instant.from(instantStr);
JSON 序列化和解析
此示例展示瞭如何在不進行額外努力的情況下將 Temporal.Instant 序列化為 JSON,以及如何將其解析回來。
js
const instant = Temporal.Instant.fromEpochMilliseconds(1627821296000);
const jsonStr = JSON.stringify({ time: instant }); // '{"time":"2021-08-01T12:34:56Z"}'
const obj = JSON.parse(jsonStr, (key, value) => {
if (key === "time") {
return Temporal.Instant.from(value);
}
return value;
});
規範
| 規範 |
|---|
| Temporal # sec-temporal.instant.prototype.tojson |
瀏覽器相容性
載入中…