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

瀏覽器相容性

另見