How to generate documents from JSON data
Turn API or database JSON into invoices and reports with DocStudio: bind paths, compute totals with expressions, choose a missing-data policy and handle diagnostics.
Most business documents are the same layout filled with different data. If the layout lives in code, every change is a code change. If the layout is a template, you change data. This article shows the data side: how JSON becomes a document.
Start with a template that reads paths
{
"schemaVersion": "1.0.0",
"body": [
{ "id": "title", "type": "text", "content": ["Order ", { "path": "order.number" }] },
{
"id": "lines",
"type": "table",
"source": { "path": "order.items" },
"columns": [
{ "id": "name", "header": "Item", "cell": { "path": "name" } },
{
"id": "total",
"header": "Total",
"align": "end",
"cell": { "fn": "mul", "args": [{ "path": "qty" }, { "path": "price" }] }
}
]
}
]
}A string in content is literal. { "path": ... } reads your data. A table's source is an array, and each column's cell is evaluated per row.
Merge the data
import { renderDocument } from 'docstudio';
const data = {
order: {
number: 'A-1042',
items: [
{ name: 'Design review', qty: 2, price: 120 },
{ name: 'Template setup', qty: 1, price: 480 },
],
},
};
const result = renderDocument(template, data, { target: 'print' });There is no schema to declare for the data. It only has to be plain JSON.
Compute, do not precompute
Totals, flags and formats belong in expressions, because then the document cannot disagree with its data:
{
"fn": "format",
"args": [
"currency",
{
"fn": "sum",
"args": [{ "path": "order.items" }],
"of": { "fn": "mul", "args": [{ "path": "qty" }, { "path": "price" }] }
},
"USD"
]
}DocStudio has 35 built-in functions. They are total: bad input gives an empty value and a diagnostic, never an exception. Nothing in a template is evaluated as JavaScript.
Decide what missing data means
Real data has gaps. config.missingData chooses the behavior:
| Policy | Result |
|---|---|
blank |
Nothing is shown |
placeholder |
A dash is shown (the default) |
warn |
Nothing is shown and a warning is returned |
error |
Nothing is shown and the render is not ok |
During design, placeholder makes gaps visible. In production, warn tells you that a field was renamed upstream, and error stops a document that must never go out incomplete.
Handle diagnostics
if (!result.ok) {
for (const item of result.diagnostics) console.error(item.code, item.path, item.message);
}Each diagnostic carries a JSON Pointer path into the template, so you can find the exact node.
Watch the limits
Data and templates are bounded before use, and a repeater has a maximum row count. Oversized input returns a LIMIT_EXCEEDED diagnostic. For very large documents, page your data rather than raising limits.
Related
Related: the matching feature page and the quick start.