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 |
浏览器兼容性
加载中…