serialize
Serializes data for embedding in a page, as JSON that is safe inside a <script type="application/json"> element.
Serializes data for embedding in a page, as JSON that is safe inside a
<script type="application/json"> element. It carries what JSON cannot: undefined, NaN,
infinities, -0, bigint, Date, URL, Map, Set, ArrayBuffer, typed arrays and DataView (copied: views
that shared a buffer come back as independent copies), plus shared references and cycles between
plain objects and arrays. Read it back with deserialize.
Import#
ts
import { serialize } from "@shadow-js/web/server";
Signature#
ts
function serialize(data: unknown): string
Parameters#
| Name | Description |
|---|---|
data |
The value to serialize. |
Returns#
JSON text with <, >, &, U+2028 and U+2029 written as \u escapes, so it cannot
close the script element.
Throws#
- TypeError
UNSERIALIZABLE_VALUEfor a function, a symbol, or an object that is not one of the supported kinds (a class instance, for example).
Examples#
ts
import { serialize } from "@shadow-js/web/server";
const data = { user: { name: "Ada" }, seen: new Set([1, 2]), at: new Date(0) };
const tag = `<script type="application/json" id="data">${serialize(data)}</script>`;