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

瀏覽器相容性

另見