# JSON Schema import and export

> Convert form schemas to JSON Schema draft 2020-12 for API validation and code generation, build forms from existing JSON Schemas, and know what does not round-trip.

`toJSONSchema()` describes the data a form produces as a [JSON Schema](https://json-schema.org/) (draft 2020-12), so your API can validate submissions with any JSON Schema validator. `fromJSONSchema()` goes the other way and builds a form from a JSON Schema you already have, for example from an OpenAPI document.

```ts
import { fromJSONSchema, toJSONSchema } from '@birchui/forms';

const jsonSchema = toJSONSchema(homeClaim);
const form = fromJSONSchema(jsonSchema);
```

## Export: `toJSONSchema(schema, options?)`

```ts
const jsonSchema = toJSONSchema(equipmentCheckout, { locale: 'en' });
```

For the [equipment checkout form](https://docs.birchui.com/forms/schema.md#form-settings), the result is an object schema with one property per field, `required` for required fields, and `title` and `description` from the form:

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "title": "Equipment checkout",
  "properties": {
    "employeeId": { "title": "Employee ID", "type": "string", "pattern": "E[0-9]{5}", "x-birchui": { "type": "text", "patternMessage": "Use the format E12345." } },
    "item": { "title": "Item", "type": "string", "enum": ["Laptop", "Projector", "Gas detector", "Thermal camera"], "x-birchui": { "type": "select" } },
    "collectOn": { "title": "Collect on", "type": "string", "format": "date", "x-birchui": { "type": "date", "width": "half" } },
    "returnBy": { "title": "Return by", "type": "string", "format": "date", "x-birchui": { "type": "date", "width": "half" } }
  },
  "required": ["employeeId", "item", "collectOn", "returnBy"]
}
```

| Option | Default | Effect |
| --- | --- | --- |
| `locale` | the schema's `locale`, or `en` | The language used for `title`, `description` and choice labels. |
| `extensions` | `true` | Adds an `x-birchui` object to each property with the form-only settings, so the form can be rebuilt. Set `false` for a clean schema to publish. |

### How fields map

| Field type | JSON Schema |
| --- | --- |
| `text` | `string` with `minLength`, `maxLength`, `pattern` |
| `email` | `string`, `format: "email"`, `maxLength` |
| `textarea` | `string` with `minLength`, `maxLength` |
| `number` | `number`, or `integer` when `integer: true`; `minimum`, `maximum` |
| `checkbox`, `toggle` | `boolean`; `const: true` when required |
| `date`, `time`, `datetime` | `string` with `format` `date`, `time` or `date-time` |
| `rating` | `integer` with `minimum` and `maximum` (1 to 5 by default) |
| `slider` | `number` with `minimum` and `maximum` (0 to 100 by default) |
| `select`, `radio` | `enum` of the values, or `oneOf` of `{ const, title }` when choices have labels |
| `multiselect`, `checkboxgroup` | `array` of the choice schema, `uniqueItems`, `minItems`, `maxItems` |
| `matrix` | `object` with one property per row, each an enum of the columns |
| `file` | `array` of base64 strings, `maxItems` |
| `signature` | `string` with `contentMediaType: "image/png"` and `contentEncoding: "base64"` |
| `computed` | `number`, or `string` when `format: 'text'`; `readOnly: true` |
| `hidden` | `string`, `number` or `boolean`, from the type of `defaultValue` |
| `dynamicpanel` | `array` of an `object` schema built from its fields; `minItems`, `maxItems` |
| `panel` | Its fields are added directly to the parent object |
| `markdown` | Left out |

`defaultValue` becomes `default`.

## Import: `fromJSONSchema(jsonSchema, options?)`

```ts
import { fromJSONSchema } from '@birchui/forms';

const technicianSchema = {
  type: 'object',
  title: 'New technician',
  required: ['name', 'region'],
  properties: {
    name: { type: 'string', title: 'Full name', maxLength: 120 },
    email: { type: 'string', format: 'email', title: 'Work email' },
    region: { type: 'string', title: 'Region', enum: ['North West', 'Midlands', 'London', 'Scotland', 'Wales'] },
    startDate: { type: 'string', format: 'date', title: 'Start date' },
    vanAssigned: { type: 'boolean', title: 'Van assigned' },
    skills: { type: 'array', title: 'Skills', items: { enum: ['Electrical', 'Gas', 'Refrigeration', 'Plumbing'] } },
    notes: { type: 'string', title: 'Notes', maxLength: 2000 },
  },
};

const warnings: string[] = [];
const schema = fromJSONSchema(technicianSchema, { onWarning: (message, path) => warnings.push(`${path}: ${message}`) });
```

When a property has an `x-birchui` annotation, its type and settings are used as they are. Otherwise the field type is inferred:

| JSON Schema | Field type |
| --- | --- |
| `enum` or `oneOf` of `const` values, up to 4 choices | `radio` |
| The same with 5 or more choices | `select` |
| `string` with `format` `email`, `date`, `time` or `date-time` | `email`, `date`, `time` or `datetime` |
| `string` with `contentMediaType: "image/..."` | `signature` |
| `string` with `maxLength` over 500 | `textarea` |
| Other `string` | `text` |
| `number`, `integer` | `number` (`integer: true` for integers) |
| `boolean` | `checkbox` |
| `array` of an enum, up to 8 choices | `checkboxgroup` |
| `array` of an enum with 9 or more choices | `multiselect` |
| `array` of objects | `dynamicpanel` |
| `array` with binary or base64 items | `file` |
| `object` whose properties share the same enum | `matrix` |
| Other `object` | `panel` |

In the example, `region` becomes a dropdown, `skills` a checkbox group and `notes` a text area. `minimum`, `maximum` (or the exclusive variants), `minLength`, `maxLength`, `pattern`, `minItems`, `maxItems`, `default`, `title` and `description` carry over. `oneOf` titles become choice labels.

Local references to `#/$defs/...` or `#/definitions/...` are resolved. Anything the importer cannot use, such as remote `$ref`s, arrays of free-form values or unknown types, is skipped and reported to `onWarning` with its path. The result is always a usable single-page form.

## What does not round-trip

With `extensions` on, exporting and importing again keeps every field and its form-only settings, such as `visibleIf`, `width`, validators, choice texts in several languages and the field type itself. Some things still change shape:

| Lost or changed | Why |
| --- | --- |
| **Pages** | JSON Schema describes data, not steps. All fields end up on one page; page titles and page `visibleIf` are lost. |
| **Panels** | Panel fields write to the parent object, so they are exported as top-level properties and the panel itself (title, collapsible state, panel-level `visibleIf`) is dropped. |
| **Markdown blocks** | They hold no data and are left out. |
| **Form settings** | Only `title` and `description` are kept. `locale`, `showProgressBar`, `showPageTitles`, button texts and `completedMessage` are lost. |
| **Translations of the form title and description** | Exported in one language. Field titles and descriptions with several translations travel in `x-birchui`. |
| **Choice `visibleIf`** | Kept only when the choices also have translated labels; otherwise choices are exported as plain values and labels. |
| **Exclusive limits** | `exclusiveMinimum` and `exclusiveMaximum` import as inclusive `min` and `max`. |
| **Everything form-only, with `extensions: false`** | Conditions, widths, validators, `computed` expressions and the exact field type are not part of JSON Schema. |

Imported nested objects without an `x-birchui` type become panels, so their fields write to the top level of the form data. If your API expects nested objects, map the submitted data before sending it.

## Validate submissions on the server

The exported schema describes the submitted data, so any JSON Schema validator can check it. File fields are an exception: the form holds `File` objects, while the schema describes base64 strings, so validate files separately from the JSON.

```ts title="server/validate-claim.ts"
import Ajv2020 from 'ajv/dist/2020';
import addFormats from 'ajv-formats';
import { toJSONSchema } from '@birchui/forms';
import { homeClaim } from '../shared/forms/home-claim';

const ajv = new Ajv2020({ strict: false });
addFormats(ajv);
const validateClaim = ajv.compile(toJSONSchema(homeClaim, { extensions: false }));

export function checkClaim(body: unknown): string[] {
  return validateClaim(body) ? [] : (validateClaim.errors ?? []).map((error) => `${error.instancePath} ${error.message}`);
}
```

Fields that are required only conditionally, through `requiredIf`, cannot be expressed in plain JSON Schema; re-check those rules with [`evaluateExpression()`](https://docs.birchui.com/forms/expressions.md#using-expressions-outside-a-form).

## In the Form Builder

The [Form Builder](https://docs.birchui.com/forms/builder.md) has **Import** and **Export** buttons for JSON Schema, and `exportJSONSchema()` and `importJSONSchema()` methods; see the [builder API](https://docs.birchui.com/forms/builder-api.md#json-schema).
