---
metadata:
  - name: generator
    content: Diplodoc Platform v5.70.2
alternate:
  - https://divkit.tech/docs/en/quickstart/typescript-json-builder.md
  - https://divkit.tech/docs/ru/quickstart/typescript-json-builder.md
  - href: https://divkit.tech/docs/en/quickstart/typescript-json-builder.md
    type: text/markdown
    title: Markdown version
  - href: https://divkit.tech/docs/en/llms.txt?revision=r22138801
    rel: describedby
---
> **Documentation Index:** Fetch the complete configuration index at https://divkit.tech/docs/en/llms.txt?revision=r22138801

# TypeScript JSON Builder

TypeScript JSON Builder is the `@divkitframework/jsonbuilder` npm package for describing DivKit layout in TypeScript. It is intended for a Node.js backend: a card is described with objects in code, and the library turns them into JSON for the client. The library classes and types are generated from the DivKit schema, so the compiler catches mistakes in property names and types.

The library source code is available on [GitHub](https://github.com/divkit/divkit/tree/main/json-builder/typescript). A similar tool for Kotlin is described on the [Kotlin DSL](https://divkit.tech/docs/en/quickstart/kotlin-dsl.md) page.

## Installation {#installation}

Install the package from npm:

```bash translate=no
npm install @divkitframework/jsonbuilder
```

The package includes CommonJS and ES module builds and TypeScript type declarations.

## Building a card {#usage}

The `divCard` function assembles a card. The first argument is the [templates](#templates) (an empty object if there are none), and the second one is an object with the [`div-data`](https://divkit.tech/docs/en/concepts/divs/2/div-data.md) structure. Layout elements are created with the constructors of the `DivText`, `DivContainer`, `DivImage`, and other classes. Property names are the same as in JSON.

```ts translate=no
import { divCard, DivText } from '@divkitframework/jsonbuilder';

const card = divCard({}, {
    // Card ID, a required property.
    log_id: 'hello_card',
    states: [
        {
            state_id: 0,
            // The card consists of a single text element.
            div: new DivText({
                font_size: 18,
                text: 'Hello, world!',
            }),
        },
    ],
});

// Serializing the card into JSON.
const json = JSON.stringify(card);
```

The serialization result (formatted for readability):

```json translate=no
{
  "templates": {},
  "card": {
    "log_id": "hello_card",
    "states": [
      {
        "state_id": 0,
        "div": {
          "type": "text",
          "font_size": 18,
          "text": "Hello, world!"
        }
      }
    ]
  }
}
```

All that remains is to send the resulting string to the client. An example of a backend that returns layout and a way to view the result in the demo app are described in the [guide to deploying a simple backend](https://divkit.tech/docs/en/quickstart/simple-backend.md).

## Templates {#templates}

[Templates](https://divkit.tech/docs/en/concepts/templates.md) are described by an object where a key is a template name and a value is an element or another template. A template parameter is declared with the `reference` function: its call is put in place of a property value. An element is created from a template with the `template` function, which takes the template name and the values of its parameters and properties.

```ts translate=no
import {
    divCard,
    DivContainer,
    DivText,
    reference,
    rewriteRefs,
    template,
    templateHelper,
    wrapContent,
} from '@divkitframework/jsonbuilder';

const templates = {
    // The title template based on a text element.
    title: new DivText({
        font_size: 18,
        width: wrapContent(),
        // The value of the text property is set by the title_text parameter.
        text: reference('title_text'),
    }),
    // The greeting template uses the title template.
    greeting: new DivContainer({
        items: [
            template('title', {
                // The title_text parameter gets the value of the greeting_text parameter.
                title_text: reference('greeting_text'),
            }),
            template('title', {
                title_text: 'Hello, DivKit!',
                // Overriding a template property.
                font_size: 14,
            }),
        ],
    }),
};
```

Before templates are passed to `divCard`, they must be processed with the `rewriteRefs` function. It returns a copy of the templates in which `reference` calls are replaced with properties that have the `$` prefix. Without it, template parameters get into JSON in an incorrect form.

The `templateHelper` function returns an object with a function for each template. Calling `tHelper.greeting({...})` is equivalent to calling `template('greeting', {...})`, but the template name is checked by the compiler.

```ts translate=no
const tHelper = templateHelper(templates);

const card = divCard(rewriteRefs(templates), {
    log_id: 'template_card',
    states: [
        {
            state_id: 0,
            // Creating an element from the greeting template.
            div: tHelper.greeting({
                // The value of the template parameter.
                greeting_text: 'Hello, world!',
            }),
        },
    ],
});
```

The templates get into the `templates` section, and the card gets into the `card` section:

```json translate=no
{
  "templates": {
    "title": {
      "type": "text",
      "font_size": 18,
      "width": {
        "type": "wrap_content"
      },
      "$text": "title_text"
    },
    "greeting": {
      "type": "container",
      "items": [
        {
          "type": "title",
          "$title_text": "greeting_text"
        },
        {
          "type": "title",
          "title_text": "Hello, DivKit!",
          "font_size": 14
        }
      ]
    }
  },
  "card": {
    "log_id": "template_card",
    "states": [
      {
        "state_id": 0,
        "div": {
          "type": "greeting",
          "greeting_text": "Hello, world!"
        }
      }
    ]
  }
}
```

{% note info %}

If the parameter name in `reference` is the same as the property name, no property with the `$` prefix is added to the template. The value of such a property is set directly by the property name when the template is used.

{% endnote %}

### Selecting the templates in use {#used-templates}

If a set of templates is shared by many cards, the JSON can include only the templates that a particular card needs. There are two functions for this:

- `thelperWithMemo` returns the `thelper` object, which is used in the same way as the result of `templateHelper`, and the `used` set with the names of the templates that were called. Use `thelper` only when building a card: `templatesDepsMap` does not see its calls inside template definitions.
- `templatesDepsMap` returns, for each template, the list of templates it depends on, including the template itself. If a template uses an undeclared template or the dependencies form a cycle, the function throws an exception.

The example continues the previous one:

```ts translate=no
import { templatesDepsMap, thelperWithMemo } from '@divkitframework/jsonbuilder';

const { thelper, used } = thelperWithMemo<typeof templates>();

const cardData = {
    log_id: 'title_card',
    states: [
        {
            state_id: 0,
            div: thelper.title({ title_text: 'Hello, world!' }),
        },
    ],
};

// The templates called while building the card, and their dependencies.
const deps = templatesDepsMap(templates);
const names = new Set([...used].flatMap((name) => deps[name]));
const usedTemplates = Object.fromEntries(
    Object.entries(templates).filter(([name]) => names.has(name)),
);

// Only the title template gets into the templates section.
const titleCard = divCard(rewriteRefs(usedTemplates), cardData);
```

## Variables and expressions {#variables-and-expressions}

[Variables](https://divkit.tech/docs/en/concepts/variables.md) are declared in the `variables` property with the `StringVariable`, `IntegerVariable`, `BooleanVariable`, and other classes. To set a [calculated expression](https://divkit.tech/docs/en/concepts/expressions.md) as a property value, pass the expression string through the `expression` function. Its result is accepted only by the properties that support expressions.

```ts translate=no
import { divCard, DivText, expression, StringVariable } from '@divkitframework/jsonbuilder';

const card = divCard({}, {
    log_id: 'variables_card',
    // Declaring variables.
    variables: [
        new StringVariable({ name: 'user_name', value: 'DivKit' }),
    ],
    states: [
        {
            state_id: 0,
            div: new DivText({
                // A constant property.
                font_size: 18,
                // A calculated property.
                text: expression('Hello, @{user_name}!'),
            }),
        },
    ],
});
```

### String escaping {#escaping}

When the result of `divCard` is serialized, plain strings are escaped: `@{` is replaced with `\@{`, and `\` is replaced with `\\`. As a result, text from external sources is not evaluated on the client as an expression and is displayed as is. For the same reason, an expression passed as a plain string without `expression` is not evaluated.

Strings created with the `expression` function get into JSON unchanged. To insert arbitrary text into an expression, escape it with the `escapeExpression` function.

```ts translate=no
import { DivText, escapeExpression, expression } from '@divkitframework/jsonbuilder';

const comment = 'Type @{name} here';

const items = [
    // A plain string. In JSON: "Type \\@{name} here", on the screen: Type @{name} here
    new DivText({ text: comment }),
    // An expression with arbitrary text. In JSON: "Type \\@{name} here: @{user_name}"
    new DivText({ text: expression(`${escapeExpression(comment)}: @{user_name}`) }),
];
```

## Type and value checks {#type-safety}

The TypeScript compiler checks:

- the names of the properties of elements and other layout objects;
- value types, allowed enumeration values, and the presence of required properties;
- that the result of `expression` is passed to a property that supports expressions;
- template names when the `templateHelper` functions are called. Template parameters are not checked in this case.

Schema entities that have the `type` property are represented by classes: `DivText`, `DivFixedSize`, `StringVariable`. The rest are described by plain objects, and their types are interfaces with the `I` prefix, such as `IDivData` and `IDivAction`. For sizes, there are short functions: `fixed`, `matchParent`, `wrapContent`, and `weighted`.

When the result of `divCard` is serialized, the `true` and `false` values are replaced with `1` and `0`.

{% note warning %}

The library does not check the values themselves. When developing cards, make sure that text strings and arrays are not empty and that the URLs of images, actions, and other properties are valid.

{% endnote %}

<!-- source: en/_includes/index/troubleshooting.md -->
## Learn more {#troubleshooting}

You can discuss topics of interest in the DivKit user community in Telegram: [https://t.me/divkit_community_en](https://t.me/divkit_community_en).



[DivKit Repository](https://github.com/divkit/divkit)
<!-- endsource: en/_includes/index/troubleshooting.md -->
