---
title: JSON schemas
project: Total.js V4
version: 0.0.99
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/json-schemas/
updated: 2026-11-16T15:41:20.819Z
---

# JSON schemas

> JSONSCHEMA(), NEWJSONSCHEMA(), String.toJSONSchema(), the jsonschemas/ directory and the supported keywords.

JSON schemas validate and convert data. They are loaded from `jsonschemas/*.json` and `jsonschemas/*.txt` files or declared with `NEWJSONSCHEMA()` and `String.toJSONSchema()`, and they are used by `JSONSCHEMA()`, by the `input`, `output`, `params` and `query` options of actions and by Total.js schemas.

Read the guide [JSON schemas](../../guides/json-schemas/) for the inline syntax, the supported keywords and examples.

## API

### JSONSCHEMA(schema, value, [callback], [error])

Type: `method` · Since: `0.0.42`

Validates and converts a value with a JSON schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `String|Object` | yes |  | Name of a registered JSON schema, or a schema object |
| `value` | `Object` | yes |  | Data to validate |
| `callback` | `Function` | no |  | `function(err, response)`; without it a promise is returned |
| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | An existing error builder to add the errors to |

Returns: `Promise|undefined` A promise when no callback is given

`schema` is the name of a registered schema (a key of `F.jsonschemas`) or a schema object. The value is converted to the types of the schema and the properties that the schema does not declare are removed.

With a callback, it calls `callback(err, response)`, where `err` is an `ErrorBuilder` or `null`. Without a callback, it returns a promise that resolves with the response or rejects with the `ErrorBuilder`. If the schema does not exist, the error is `404`.

`JSONSCHEMA()` always validates all properties; for partial validation use the `transform()` method of the schema object.

Example: Callback
```js
JSONSCHEMA('product', { name: 'Table', price: '120.5' }, function(err, response) {
	if (err)
		console.log(err.items);
	else
		console.log(response.price); // 120.5
});
```

Example: Promise
```js
var model = await JSONSCHEMA('product', $.body);
```

### NEWJSONSCHEMA(name, [declaration])

Type: `method` · Since: `0.0.42`

Registers or removes a JSON schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String|Object` | yes |  | Name of the schema, or a schema object with `$id` |
| `declaration` | `String` | no |  | Inline declaration such as `'name:String, *email:Email'`; omit it to remove the schema |

- `NEWJSONSCHEMA(object)` registers a schema object under its `$id`.
- `NEWJSONSCHEMA(name, declaration)` converts an inline declaration with `String.toJSONSchema(name)` and registers it under `name`.
- `NEWJSONSCHEMA(name)` without a declaration removes the schema.

A schema object registered with `NEWJSONSCHEMA(object)` is stored as it is, without the `transform()` method. Use it with `JSONSCHEMA()`; for actions, prefer a file in `jsonschemas/` or an inline declaration.

Example: Inline declaration
```js
NEWJSONSCHEMA('Contact', 'name:String(50), *email:Email, phone:Phone');
```

Example: Remove
```js
NEWJSONSCHEMA('Contact');
```

### String.toJSONSchema([name], [url])

Type: `method` · Since: `0.0.42`

Converts an inline declaration to a JSON schema object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no |  | Name to register the schema under; it is also used in `$id` |
| `url` | `String` | no | `CONF.url or https://schemas.totaljs.com/` | Base URL of `$id` |

Returns: `Object` The JSON schema object

Parses `name:Type` pairs separated by commas or new lines and returns a JSON schema object with `type: 'object'`, `properties`, `required` and a `transform()` method. With `name`, the schema is also registered in `F.jsonschemas`.

The `$id` is `url + name + '.json'`. The default URL is `CONF.url`, or `https://schemas.totaljs.com/`; without a name a hash of the declaration is used. `$schema` is `https://json-schema.org/draft/2020-12/schema`.

| Syntax | Result |
| --- | --- |
| `*name`, `!name` | Required property |
| `name:String(50)` | `maxLength: 50` |
| `name:[Type]` | Array of a type |
| `name:{a\|b\|c}` | String enum (`;` works too) |
| `name:{a:String, b:Number}` | Nested object |
| `name:[{a:String}]` | Array of nested objects |
| `name:@Other` | Another Total.js schema, JSON schema or action input |

`@Other` throws an error if nothing with that name exists.

Example: Nested objects and enums
```js
var schema = '*name:String(100), role:{admin|user}, address:{street:String, city:String}, items:[{id:UID, qty:Number}]'.toJSONSchema('order');
var res = schema.transform({ name: 'Peter', role: 'user', items: [{ id: '', qty: '2' }] });
```

### jsonschema.transform(value, [partial], [error])

Type: `method` · Since: `0.0.66`

Validates a value with this schema object and returns the result synchronously.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | Data to validate |
| `partial` | `Boolean` | no | `false` | Validate only the properties present in the value |
| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | An existing error builder to add the errors to |

Returns: `Object` `{ error: ErrorBuilder|null, response: Object }`

Schema objects from `jsonschemas/` files and from `String.toJSONSchema()` have this method. It returns `{ error, response }`: `error` is an `ErrorBuilder` with the errors or `null`, and `response` is the converted value.

With `partial`, properties that are `undefined` in the value are skipped, so missing required properties are not errors. This applies at every level, also to the properties of nested objects.

Example: Partial update
```js
var schema = F.jsonschemas.product;
var res = schema.transform({ price: '99' }, true);
if (res.error)
	$.invalid(res.error);
else
	$.success();
```

### F.jsonschemas

Type: `property`

All registered JSON schemas, by name and by `$id`.

Returns: `Object` Schema objects by key

An object with every registered schema. Files from `jsonschemas/` are stored under their file name (and under `$id` for `.json` files), `NEWJSONSCHEMA()` and `String.toJSONSchema(name)` under the name, and converted Total.js schemas under the schema name and their `$id`.

Example: Read a schema
```js
var schema = F.jsonschemas.product;
console.log(Object.keys(schema.properties));
```

### directory_jsonschemas : /jsonschemas/

Type: `config` · Since: `0.0.42`

The directory with JSON schema files.

Returns: `String` Default `/jsonschemas/`

The framework reads `.json` and `.txt` files from this directory and its subdirectories when the application starts. Set the option to an empty value to disable loading.

Example: config
```text
directory_jsonschemas : /schemas/json/
```

### PATH.jsonschemas([filename])

Type: `method`

Returns the path to the JSON schemas directory or to a file in it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name |

Returns: `String` The path

Combines `CONF.directory_jsonschemas` with `filename`.

Example: Read a file
```js
var raw = require('fs').readFileSync(PATH.jsonschemas('product.json'), 'utf8');
```

### jsonschemas/{name}.json

Type: `type` · Since: `0.0.42`

A JSON schema in a JSON file.

A standard JSON schema object, read at start. It is registered under the file name without the extension (with the subdirectory, e.g. `users/address`) and under its `$id`. The framework adds the `transform()` method. An invalid file is reported as an error and skipped.

Example: jsonschemas/user.json
```json
{
	"$id": "https://example.com/user.json",
	"type": "object",
	"properties": {
		"name": { "type": "string", "subtype": "name", "maxLength": 50 },
		"email": { "type": "string", "subtype": "email" },
		"role": { "type": "string", "enum": ["admin", "user"] }
	},
	"required": ["name", "email"]
}
```

### jsonschemas/{name}.txt

Type: `type` · Since: `0.0.92`

A JSON schema written in the inline syntax.

The content is converted with `String.toJSONSchema()` and registered under the file name without the extension. Write one property per line or separate them with commas.

Example: jsonschemas/user.txt
```text
*name:Name(50)
*email:Email
role:{admin|user}
tags:[String]
```

### { "type": "string", "subtype": "..." }

Type: `type`

A string property, optionally with a subtype.

Values that are not strings are converted to strings; empty values become `null`. The `subtype` keyword adds formatting or a check: `email`, `phone`, `url`, `zip`, `guid`, `uid`, `json`, `base64`, `color`, `icon`, `name`, `lower`/`lowercase`, `upper`/`uppercase`, `capitalize` and `capitalize2`. String keywords: `minLength`, `maxLength`, `enum`.

Example: JSON
```json
{ "type": "string", "subtype": "email", "maxLength": 120 }
```

### { "type": "number" }

Type: `type`

A number property; `integer` is accepted as a type name too.

Strings with digits are parsed with `String.parseFloat()`; other values become `null`. The `smallint` subtype allows -32767 to 32767 and `tinyint` 0 to 255. Number keywords: `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf`. The value is not rounded, even for the `int` subtype.

Example: JSON
```json
{ "type": "number", "minimum": 1, "maximum": 100 }
```

### { "type": "boolean" }

Type: `type`

A boolean property; `bool` is accepted too.

Values that are not booleans are parsed with `String.parseBoolean()`.

Example: JSON
```json
{ "type": "boolean" }
```

### { "type": "date" }

Type: `type`

A date property (a Total.js extension of JSON schema).

Values that are not `Date` objects are parsed with `String.parseDate()`. An invalid date becomes `null`; it is an error only when the property is required.

Example: JSON
```json
{ "type": "date" }
```

### { "type": "object", "properties": {...} }

Type: `type`

An object property, validated by its own `properties`.

Only the declared `properties` are copied to the response. An object without `properties` is copied as it is. Object keywords: `properties`, `required`, `minProperties`, `$ref`.

Example: JSON
```json
{
	"type": "object",
	"properties": {
		"street": { "type": "string" },
		"city": { "type": "string" }
	},
	"required": ["city"]
}
```

### { "type": "array", "items": {...} }

Type: `type`

An array property; each item is validated by `items`.

Without `items` the array is copied as it is (with duplicates removed when `uniqueItems` is set). Invalid items are left out and their errors are reported. Array keywords: `items`, `minItems`, `uniqueItems`.

Example: JSON
```json
{ "type": "array", "items": { "type": "string", "subtype": "email" }, "minItems": 1 }
```

### "required": ["name", ...]

Type: `property`

The list of required properties of an object.

A required property that is missing, empty or invalid is an error named after the property. In the inline syntax, start the name with `*` or `!`. With partial validation, missing properties are skipped.

Example: JSON
```json
{ "type": "object", "properties": { "name": { "type": "string" } }, "required": ["name"] }
```

### "properties": { ... }

Type: `property`

The properties of an object and their schemas.

Each key is a property name and each value its schema. Properties that are not declared are removed from the response.

Example: JSON
```json
{ "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "number" } } }
```

### "subtype": "email"

Type: `property`

A Total.js keyword that adds a format check or a conversion to strings and numbers.

String subtypes: `email`, `phone`, `url`, `zip`, `guid`, `uid`, `json`, `base64`, `color` (`#RGB`, `#RRGGBB`, `#RRGGBBAA`), `icon` (Font Awesome or Total.js Icons classes), `name`, `lower`, `lowercase`, `upper`, `uppercase`, `capitalize`, `capitalize2`. Number subtypes with a check: `smallint`, `tinyint`. `String.toJSONSchema()` sets the subtype from the type name.

Example: JSON
```json
{ "type": "string", "subtype": "phone" }
```

### "maxLength": 50

Type: `property`

The maximum length of a string.

A longer string is an error. In the inline syntax, write `String(50)`.

Example: JSON
```json
{ "type": "string", "maxLength": 50 }
```

### "minLength": 3

Type: `property`

The minimum length of a non-empty string.

A shorter string is an error. An empty value is checked only by `required`.

Example: JSON
```json
{ "type": "string", "minLength": 3 }
```

### "enum": ["a", "b"]

Type: `property`

The allowed values of a string.

A value that is not in the list is an error. An empty value is allowed unless the property is required. In the inline syntax, write `{a|b}`.

Example: JSON
```json
{ "type": "string", "enum": ["draft", "published"] }
```

### "minimum": 1

Type: `property`

The smallest allowed number.

A smaller number is an error.

Example: JSON
```json
{ "type": "number", "minimum": 1 }
```

### "maximum": 100

Type: `property`

The largest allowed number.

A larger number is an error.

Example: JSON
```json
{ "type": "number", "maximum": 100 }
```

### "exclusiveMinimum": 0.5

Type: `property`

The number must be greater than this value.

A number less than or equal to the value is an error.

Example: JSON
```json
{ "type": "number", "exclusiveMinimum": 0.5 }
```

### "exclusiveMaximum": 10

Type: `property`

The number must be smaller than this value.

A number greater than or equal to the value is an error.

Example: JSON
```json
{ "type": "number", "exclusiveMaximum": 10 }
```

### "multipleOf": 5

Type: `property`

The number must be a multiple of this value.

A number with a remainder is an error.

Example: JSON
```json
{ "type": "number", "multipleOf": 5 }
```

### "items": { ... }

Type: `property`

The schema of the items of an array.

Each item is validated by this schema; invalid items are left out and reported. The schema may be a simple type, an object with `properties`, or a `$ref`.

Example: JSON
```json
{ "type": "array", "items": { "type": "number" } }
```

### "minItems": 1

Type: `property`

The minimum number of valid items in an array.

Counted after invalid items are removed. An empty array of a required property is always an error.

Example: JSON
```json
{ "type": "array", "items": { "type": "string" }, "minItems": 1 }
```

### "uniqueItems": true

Type: `property`

Removes duplicate items from an array.

Duplicates are removed silently; they are not an error. Objects are compared by reference, so the option is useful for simple values.

Example: JSON
```json
{ "type": "array", "items": { "type": "string" }, "uniqueItems": true }
```

### "minProperties": 1

Type: `property`

The minimum number of valid properties in an object.

Counts the properties that end in the response.

Example: JSON
```json
{ "type": "object", "properties": { "a": { "type": "string" }, "b": { "type": "string" } }, "minProperties": 1 }
```

### "$ref": "name"

Type: `property`

Uses another registered JSON schema for a property.

A property without `type` and with `$ref` is validated by the schema `F.jsonschemas[$ref]`: the name of a file in `jsonschemas/`, a name from `NEWJSONSCHEMA()` or an `$id`. If the schema does not exist, it is an error. In the inline syntax, `@Name` embeds the other schema instead.

Example: JSON
```json
{ "type": "object", "properties": { "address": { "$ref": "address" } } }
```

### schema.toJSONSchema()

Type: `method`

Converts a Total.js schema to a JSON schema object.

Returns: `Object` The JSON schema object

Converts the fields of the schema (and the fields from `schema.jsonschema_define()`) to `properties` and the required fields to `required`. The `$id` is `CONF.url` (or `https://schemas.totaljs.com/`) + the schema name + `.json`. The result is registered in `F.jsonschemas` under the schema name and the `$id`.

Example: Export
```js
var json = GETSCHEMA('Order').toJSONSchema();
console.log(JSON.stringify(json, null, '\t'));
```

### schema.jsonschema_define(name, type, [required], [invalid])

Type: `method` · Since: `0.0.42`

Declares a field that appears only in the JSON schema made by `schema.toJSONSchema()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String|Array` | yes |  | Field name or names |
| `type` | `String|Object` | yes |  | Field type as in `schema.define()`, or `null` to remove |
| `required` | `Boolean` | no | `false` | Marks the field as required |
| `invalid` | `String` | no | `'@'` | Error message |

Returns: `Function` A function that sets a default value and returns the schema

The field uses the same types as `schema.define()`, but it does not take part in the normal validation of the Total.js schema. `type` set to `null` removes the field. `name` may be an array of names. A string as the third argument is the error message and makes the field required.

Example: Extra field
```js
NEWSCHEMA('Order', function(schema) {
	schema.define('id', UID);
	schema.jsonschema_define('url', 'URL', true);
});
```

### $MAKE(schema, model, [callback], [novalidate], [arg], [controller])

Type: `method`

Makes and validates a model of a Total.js schema synchronously.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `String` | yes |  | Name of the Total.js schema |
| `model` | `Object` | yes |  | Data |
| `callback` | `Function` | no |  | `function(err, response, arg)` |
| `novalidate` | `Boolean` | no | `false` | Skip validation |
| `arg` | `Object` | no |  | A value passed to the callback |
| `controller` | `Controller|SchemaOptions` | no |  | Context of the request |

Returns: `Object` The made model

Calls `schema.make()` and returns the made model. Errors go to `callback(err, response, arg)`. With `novalidate`, the model is converted but not validated. For a promise use `MAKE()` (see [Schemas](../schemas/)). Returns `undefined` if the schema does not exist.

Example: Make
```js
$MAKE('Order', $.body, function(err, model) {
	if (err)
		$.invalid(err);
	else
		$.success(model.id);
});
```

### $CREATE(schema)

Type: `method`

Creates a new model of a Total.js schema with default values.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `String` | yes |  | Name of the Total.js schema |

Returns: `Object|null` A new model with default values

Returns the default object of the schema (`schema.default()`), or `null` if the schema does not exist. The defaults come from the fields of the Total.js schema.

Example: Defaults
```js
var order = $CREATE('Order');
```
