Format HTML for JSON
Turn an HTML file into the content of an HTML block: extract the body, keep its styles, and escape it as JSON
In this guide, you turn an HTML file, such as the output of an HTML editor or a template engine, into a valid request body for an HTML content block.
Sending HTML in JSON has the following pitfalls:
- Double quotes in the HTML must be escaped in the JSON string.
- Editors output a full document with
<html>and<body>, but an HTML block holds a fragment. - Styles on
<body>, such as padding and fonts, are lost unless you move them to a wrapper element.
Before you begin
- Store your API key in the
SAJN_API_KEYenvironment variable. To create a key, go to workspace settings in the sajn app, then Utvecklare (Developer) > API-nycklar (API keys). - Have a
DRAFTdocument. For more information, see Create a document.
Send an HTML file
Extract the body and keep its styles
The following functions return the content of <body>, wrapped in a <div> with the body's style attribute. Content without a <body> tag with attributes is returned unchanged:
/**
* Formats HTML content for a sajn HTML block.
* Extracts body content and preserves body styles.
*/
function formatHtmlFieldPayload(htmlContent: string) {
const trimmed = htmlContent.trim();
// Check if content has a body tag with attributes
const bodyStartMatch = trimmed.match(/<body\s+/i);
if (!bodyStartMatch || bodyStartMatch.index === undefined) {
// No body tag found, return content as-is
return {
type: "HTML",
fieldMeta: {
type: "HTML",
content: trimmed,
},
};
}
// Find the end of the opening body tag
const bodyStartPos = bodyStartMatch.index;
const bodyTagEndPos = trimmed.indexOf(">", bodyStartPos);
if (bodyTagEndPos === -1) {
return {
type: "HTML",
fieldMeta: { type: "HTML", content: trimmed },
};
}
// Extract the body tag and find closing tag
const bodyTag = trimmed.slice(bodyStartPos, bodyTagEndPos + 1);
const bodyEndMatch = trimmed.slice(bodyTagEndPos + 1).match(/<\/body>/i);
if (!bodyEndMatch || bodyEndMatch.index === undefined) {
return {
type: "HTML",
fieldMeta: { type: "HTML", content: trimmed },
};
}
// Extract body content
const bodyContentStart = bodyTagEndPos + 1;
const bodyContentEnd = bodyTagEndPos + 1 + bodyEndMatch.index;
const bodyContent = trimmed.slice(bodyContentStart, bodyContentEnd).trim();
// Extract style attribute from body tag
const styleMatch =
bodyTag.match(/style\s*=\s*"([^"]*)"/i) ||
bodyTag.match(/style\s*=\s*'([^']*)'/i);
// Wrap content in div, preserving body styles
const processedHtml = styleMatch
? `<div style="${styleMatch[1].trim()}">${bodyContent}</div>`
: `<div>${bodyContent}</div>`;
return {
type: "HTML",
fieldMeta: {
type: "HTML",
content: processedHtml,
},
};
}For example, the functions turn the following document:
<html>
<head><title>Agreement</title></head>
<body style="margin: 0; padding: 30px; font-family: Georgia, serif;">
<h1 style="color: #003366;">Service agreement</h1>
<p>Effective from 2026-11-01</p>
</body>
</html>Into the following fragment:
<div style="margin: 0; padding: 30px; font-family: Georgia, serif;"><h1 style="color: #003366;">Service agreement</h1>
<p>Effective from 2026-11-01</p></div>Send the fragment as an HTML block
Build the body with your language's JSON serializer, which escapes the quotes for you. Never build the JSON string by hand. The block goes in a content array:
import { readFile } from "node:fs/promises";
const html = await readFile("document.html", "utf8");
const { fieldMeta } = formatHtmlFieldPayload(html);
const response = await fetch(
`https://app.sajn.se/api/v1/documents/${process.env.DOCUMENT_ID}/content`,
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.SAJN_API_KEY}`,
"Sajn-Version": "2026-10",
"Content-Type": "application/json",
},
body: JSON.stringify({ content: [{ type: "HTML", position: 0, fieldMeta }] }),
},
);
const body = await response.json();
if (!response.ok) {
throw new Error(`${body.code}: ${body.message} (request ${body.requestId})`);
}
console.log(body.data[0].id);Set DOCUMENT_ID in the environment to the ID of the draft document. The response has the created block in data.
Prepare the HTML
- Use inline
styleattributes only. sajn removes<style>tags, so styles from a stylesheet or a<head>are lost. - Split long content into several HTML blocks, ordered by
position, instead of one large block. - Host images and reference them by
httpsURL instead of inlining them as base64.
For every allowed tag and CSS property, see HTML content.
Handle errors
400 INVALID_JSON: the body isn't valid JSON, usually because of unescaped quotes. Serialize the body withJSON.stringifyorjson.400 VALIDATION_FAILEDoncontent.0.fieldMeta.type:typeandfieldMeta.typemust both beHTML.
For the error shape and every code, see Errors.
Next steps
Was this page helpful?
Last updated on