serializeData
Serialize JSON safely for embedding in an HTML script element.
Compatibility
Import from @kasperrt/smolter/utils
Signature
function serializeData(value: unknown): string;Parameters
Accepts a JSON-serializable value. It does not await promises, detect data routes, or normalize errors; resolve application data before calling it.
Returns
Returns JSON text with less-than characters and Unicode line/paragraph separators escaped. JSON.parse restores the original values, while the escaped text cannot inject a closing script tag through a string value.
Example
Use the serialized string as script text, not as an HTML attribute value. The application document helpers already use this for hydration payloads and JSON-LD.
import { serializeData } from "@kasperrt/smolter/utils";
const payload = serializeData({ title: "<Task list>" });
const script = `<script type="application/json" id="page-data">${payload}</script>`;JSON limits
The input must produce JSON text: top-level undefined, functions, and symbols are unsupported, as are cyclic objects and BigInt without custom serialization. Native JSON rules apply to object fields and custom toJSON methods. This helper is not a sanitizer for arbitrary HTML or executable JavaScript.