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