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

# Schemi JSON

> JSONSCHEMA(), NEWJSONSCHEMA(), String.toJSONSchema(), la directory jsonschemas/ e le parole chiave supportate.

Gli schemi JSON validano e convertono i dati. Vengono caricati dai file `jsonschemas/*.json` e `jsonschemas/*.txt` oppure dichiarati con `NEWJSONSCHEMA()` e `String.toJSONSchema()`, e vengono usati da `JSONSCHEMA()`, dalle opzioni `input`, `output`, `params` e `query` delle azioni e dagli schemi Total.js.

Leggi la guida [Schemi JSON](../../guides/json-schemas/) per la sintassi inline, le parole chiave supportate e gli esempi.

## API

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

Type: `method` · Since: `0.0.42`

Valida e converte un valore con uno schema JSON.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `String|Object` | yes |  | Nome di uno schema JSON registrato, o un oggetto schema |
| `value` | `Object` | yes |  | Dati da validare |
| `callback` | `Function` | no |  | `function(err, response)`; senza di essa viene restituita una promise |
| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | Un error builder esistente a cui aggiungere gli errori |

Returns: `Promise|undefined` Una promise quando non viene passata una callback

`schema` è il nome di uno schema registrato (una chiave di `F.jsonschemas`) o un oggetto schema. Il valore viene convertito nei tipi dello schema e le proprietà che lo schema non dichiara vengono rimosse.

Con una callback chiama `callback(err, response)`, dove `err` è un `ErrorBuilder` o `null`. Senza callback restituisce una promise che si risolve con la risposta o viene rifiutata con l'`ErrorBuilder`. Se lo schema non esiste, l'errore è `404`.

`JSONSCHEMA()` valida sempre tutte le proprietà; per la validazione parziale usa il metodo `transform()` dell'oggetto schema.

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`

Registra o rimuove uno schema JSON.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String|Object` | yes |  | Nome dello schema, o un oggetto schema con `$id` |
| `declaration` | `String` | no |  | Dichiarazione inline come `'name:String, *email:Email'`; omettila per rimuovere lo schema |

- `NEWJSONSCHEMA(object)` registra un oggetto schema con il suo `$id`.
- `NEWJSONSCHEMA(name, declaration)` converte una dichiarazione inline con `String.toJSONSchema(name)` e la registra come `name`.
- `NEWJSONSCHEMA(name)` senza dichiarazione rimuove lo schema.

Un oggetto schema registrato con `NEWJSONSCHEMA(object)` viene salvato così com'è, senza il metodo `transform()`. Usalo con `JSONSCHEMA()`; per le azioni preferisci un file in `jsonschemas/` o una dichiarazione inline.

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

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

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

Type: `method` · Since: `0.0.42`

Converte una dichiarazione inline in un oggetto schema JSON.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no |  | Nome con cui registrare lo schema; viene usato anche in `$id` |
| `url` | `String` | no | `CONF.url or https://schemas.totaljs.com/` | URL di base di `$id` |

Returns: `Object` L'oggetto schema JSON

Interpreta coppie `name:Type` separate da virgole o da a capo e restituisce un oggetto schema JSON con `type: 'object'`, `properties`, `required` e un metodo `transform()`. Con `name`, lo schema viene anche registrato in `F.jsonschemas`.

L'`$id` è `url + name + '.json'`. L'URL predefinito è `CONF.url`, oppure `https://schemas.totaljs.com/`; senza nome viene usato un hash della dichiarazione. `$schema` è `https://json-schema.org/draft/2020-12/schema`.

| Sintassi | Risultato |
| --- | --- |
| `*name`, `!name` | Proprietà obbligatoria |
| `name:String(50)` | `maxLength: 50` |
| `name:[Type]` | Array di un tipo |
| `name:{a\|b\|c}` | Enum di stringhe (funziona anche `;`) |
| `name:{a:String, b:Number}` | Oggetto annidato |
| `name:[{a:String}]` | Array di oggetti annidati |
| `name:@Other` | Un altro schema Total.js, schema JSON o input di un'azione |

`@Other` lancia un errore se non esiste nulla con quel nome.

Example: Oggetti annidati ed enum
```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`

Valida un valore con questo oggetto schema e restituisce il risultato in modo sincrono.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | Dati da validare |
| `partial` | `Boolean` | no | `false` | Valida solo le proprietà presenti nel valore |
| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | Un error builder esistente a cui aggiungere gli errori |

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

Gli oggetti schema dei file `jsonschemas/` e di `String.toJSONSchema()` hanno questo metodo. Restituisce `{ error, response }`: `error` è un `ErrorBuilder` con gli errori oppure `null`, e `response` è il valore convertito.

Con `partial`, le proprietà che sono `undefined` nel valore vengono saltate, quindi le proprietà obbligatorie mancanti non sono errori. Questo vale a ogni livello, anche per le proprietà degli oggetti annidati.

Example: Aggiornamento parziale
```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`

Tutti gli schemi JSON registrati, per nome e per `$id`.

Returns: `Object` Oggetti schema per chiave

Un oggetto con ogni schema registrato. I file di `jsonschemas/` vengono salvati con il nome del file (e con `$id` per i file `.json`), `NEWJSONSCHEMA()` e `String.toJSONSchema(name)` con il nome, e gli schemi Total.js convertiti con il nome dello schema e il loro `$id`.

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

### directory_jsonschemas : /jsonschemas/

Type: `config` · Since: `0.0.42`

La directory con i file degli schemi JSON.

Returns: `String` Predefinito `/jsonschemas/`

Il framework legge i file `.json` e `.txt` da questa directory e dalle sue sottodirectory all'avvio dell'applicazione. Imposta l'opzione a un valore vuoto per disattivare il caricamento.

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

### PATH.jsonschemas([filename])

Type: `method`

Restituisce il percorso della directory degli schemi JSON o di un file al suo interno.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file |

Returns: `String` Il percorso

Combina `CONF.directory_jsonschemas` con `filename`.

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

### jsonschemas/{name}.json

Type: `type` · Since: `0.0.42`

Uno schema JSON in un file JSON.

Un oggetto schema JSON standard, letto all'avvio. Viene registrato con il nome del file senza estensione (con la sottodirectory, ad es. `users/address`) e con il suo `$id`. Il framework aggiunge il metodo `transform()`. Un file non valido viene segnalato come errore e ignorato.

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`

Uno schema JSON scritto con la sintassi inline.

Il contenuto viene convertito con `String.toJSONSchema()` e registrato con il nome del file senza estensione. Scrivi una proprietà per riga oppure separale con virgole.

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

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

Type: `type`

Una proprietà stringa, eventualmente con un sottotipo.

I valori che non sono stringhe vengono convertiti in stringhe; i valori vuoti diventano `null`. La parola chiave `subtype` aggiunge una formattazione o un controllo: `email`, `phone`, `url`, `zip`, `guid`, `uid`, `json`, `base64`, `color`, `icon`, `name`, `lower`/`lowercase`, `upper`/`uppercase`, `capitalize` e `capitalize2`. Parole chiave per le stringhe: `minLength`, `maxLength`, `enum`.

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

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

Type: `type`

Una proprietà numerica; anche `integer` è accettato come nome di tipo.

Le stringhe con cifre vengono interpretate con `String.parseFloat()`; gli altri valori diventano `null`. Il sottotipo `smallint` ammette da -32767 a 32767 e `tinyint` da 0 a 255. Parole chiave per i numeri: `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf`. Il valore non viene arrotondato, nemmeno con il sottotipo `int`.

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

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

Type: `type`

Una proprietà booleana; è accettato anche `bool`.

I valori che non sono booleani vengono interpretati con `String.parseBoolean()`.

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

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

Type: `type`

Una proprietà data (un'estensione Total.js dello schema JSON).

I valori che non sono oggetti `Date` vengono interpretati con `String.parseDate()`. Una data non valida diventa `null`; è un errore solo quando la proprietà è obbligatoria.

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

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

Type: `type`

Una proprietà oggetto, validata dalle sue `properties`.

Nella risposta vengono copiate solo le `properties` dichiarate. Un oggetto senza `properties` viene copiato così com'è. Parole chiave per gli oggetti: `properties`, `required`, `minProperties`, `$ref`.

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

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

Type: `type`

Una proprietà array; ogni elemento viene validato da `items`.

Senza `items` l'array viene copiato così com'è (con i duplicati rimossi quando è impostato `uniqueItems`). Gli elementi non validi vengono esclusi e i loro errori vengono segnalati. Parole chiave per gli array: `items`, `minItems`, `uniqueItems`.

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

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

Type: `property`

L'elenco delle proprietà obbligatorie di un oggetto.

Una proprietà obbligatoria mancante, vuota o non valida è un errore con il nome della proprietà. Nella sintassi inline, fai iniziare il nome con `*` o `!`. Con la validazione parziale, le proprietà mancanti vengono saltate.

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

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

Type: `property`

Le proprietà di un oggetto e i loro schemi.

Ogni chiave è il nome di una proprietà e ogni valore il suo schema. Le proprietà non dichiarate vengono rimosse dalla risposta.

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

### "subtype": "email"

Type: `property`

Una parola chiave Total.js che aggiunge un controllo di formato o una conversione a stringhe e numeri.

Sottotipi di stringa: `email`, `phone`, `url`, `zip`, `guid`, `uid`, `json`, `base64`, `color` (`#RGB`, `#RRGGBB`, `#RRGGBBAA`), `icon` (classi Font Awesome o Total.js Icons), `name`, `lower`, `lowercase`, `upper`, `uppercase`, `capitalize`, `capitalize2`. Sottotipi numerici con controllo: `smallint`, `tinyint`. `String.toJSONSchema()` imposta il sottotipo in base al nome del tipo.

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

### "maxLength": 50

Type: `property`

La lunghezza massima di una stringa.

Una stringa più lunga è un errore. Nella sintassi inline, scrivi `String(50)`.

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

### "minLength": 3

Type: `property`

La lunghezza minima di una stringa non vuota.

Una stringa più corta è un errore. Un valore vuoto viene controllato solo da `required`.

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

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

Type: `property`

I valori ammessi di una stringa.

Un valore che non è nell'elenco è un errore. Un valore vuoto è ammesso, a meno che la proprietà non sia obbligatoria. Nella sintassi inline, scrivi `{a|b}`.

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

### "minimum": 1

Type: `property`

Il numero più piccolo ammesso.

Un numero più piccolo è un errore.

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

### "maximum": 100

Type: `property`

Il numero più grande ammesso.

Un numero più grande è un errore.

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

### "exclusiveMinimum": 0.5

Type: `property`

Il numero deve essere maggiore di questo valore.

Un numero minore o uguale al valore è un errore.

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

### "exclusiveMaximum": 10

Type: `property`

Il numero deve essere minore di questo valore.

Un numero maggiore o uguale al valore è un errore.

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

### "multipleOf": 5

Type: `property`

Il numero deve essere un multiplo di questo valore.

Un numero con un resto è un errore.

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

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

Type: `property`

Lo schema degli elementi di un array.

Ogni elemento viene validato da questo schema; gli elementi non validi vengono esclusi e segnalati. Lo schema può essere un tipo semplice, un oggetto con `properties` o un `$ref`.

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

### "minItems": 1

Type: `property`

Il numero minimo di elementi validi in un array.

Il conteggio avviene dopo la rimozione degli elementi non validi. Un array vuoto di una proprietà obbligatoria è sempre un errore.

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

### "uniqueItems": true

Type: `property`

Rimuove gli elementi duplicati da un array.

I duplicati vengono rimossi in silenzio; non sono un errore. Gli oggetti vengono confrontati per riferimento, quindi l'opzione è utile per i valori semplici.

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

### "minProperties": 1

Type: `property`

Il numero minimo di proprietà valide in un oggetto.

Conta le proprietà che finiscono nella risposta.

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

### "$ref": "name"

Type: `property`

Usa un altro schema JSON registrato per una proprietà.

Una proprietà senza `type` e con `$ref` viene validata dallo schema `F.jsonschemas[$ref]`: il nome di un file in `jsonschemas/`, un nome di `NEWJSONSCHEMA()` o un `$id`. Se lo schema non esiste, è un errore. Nella sintassi inline, `@Name` incorpora invece l'altro schema.

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

### schema.toJSONSchema()

Type: `method`

Converte uno schema Total.js in un oggetto schema JSON.

Returns: `Object` L'oggetto schema JSON

Converte i campi dello schema (e i campi di `schema.jsonschema_define()`) in `properties` e i campi obbligatori in `required`. L'`$id` è `CONF.url` (o `https://schemas.totaljs.com/`) + il nome dello schema + `.json`. Il risultato viene registrato in `F.jsonschemas` con il nome dello schema e con l'`$id`.

Example: Esportazione
```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`

Dichiara un campo che compare solo nello schema JSON creato da `schema.toJSONSchema()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String|Array` | yes |  | Nome o nomi del campo |
| `type` | `String|Object` | yes |  | Tipo del campo come in `schema.define()`, oppure `null` per rimuoverlo |
| `required` | `Boolean` | no | `false` | Contrassegna il campo come obbligatorio |
| `invalid` | `String` | no | `'@'` | Messaggio di errore |

Returns: `Function` Una funzione che imposta un valore predefinito e restituisce lo schema

Il campo usa gli stessi tipi di `schema.define()`, ma non partecipa alla normale validazione dello schema Total.js. `type` impostato a `null` rimuove il campo. `name` può essere un array di nomi. Una stringa come terzo argomento è il messaggio di errore e rende il campo obbligatorio.

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

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

Type: `method`

Crea e valida in modo sincrono un modello di uno schema Total.js.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `String` | yes |  | Nome dello schema Total.js |
| `model` | `Object` | yes |  | Dati |
| `callback` | `Function` | no |  | `function(err, response, arg)` |
| `novalidate` | `Boolean` | no | `false` | Salta la validazione |
| `arg` | `Object` | no |  | Un valore passato alla callback |
| `controller` | `Controller|SchemaOptions` | no |  | Contesto della richiesta |

Returns: `Object` Il modello creato

Chiama `schema.make()` e restituisce il modello creato. Gli errori vanno a `callback(err, response, arg)`. Con `novalidate` il modello viene convertito ma non validato. Per una promise usa `MAKE()` (vedi [Schemi](../schemas/)). Restituisce `undefined` se lo schema non esiste.

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

### $CREATE(schema)

Type: `method`

Crea un nuovo modello di uno schema Total.js con i valori predefiniti.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `String` | yes |  | Nome dello schema Total.js |

Returns: `Object|null` Un nuovo modello con i valori predefiniti

Restituisce l'oggetto predefinito dello schema (`schema.default()`), oppure `null` se lo schema non esiste. I valori predefiniti provengono dai campi dello schema Total.js.

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