← Retour au Blog

Comprendre JSON Schema : Validation et documentation des données

Maîtrisez JSON Schema pour valider vos données JSON. Guide complet avec exemples pratiques, types, validations et outils pour créer des schémas robustes.

Big JSON Team15 min de lectureadvanced
B

Big JSON Team

Technical Writer

Expert in JSON data manipulation, API development, and web technologies. Passionate about creating tools that make developers' lives easier.

15 min de lecture

# Comprendre JSON Schema : Validation et documentation des données

JSON Schema est un vocabulaire puissant pour annoter et valider des documents JSON. Ce guide vous apprend à créer des schémas robustes pour valider vos données.

Qu'est-ce que JSON Schema ?

JSON Schema est un standard pour décrire la structure et les contraintes de données JSON. Il permet de :

  • Valider les données
  • Documenter les API
  • Générer du code
  • Créer des formulaires UI

Exemple simple

Données JSON :

\\\json

{

"nom": "Jean Dupont",

"age": 30,

"email": "jean@exemple.com"

}

\\\

JSON Schema :

\\\json

{

"$schema": "http://json-schema.org/draft-07/schema#",

"type": "object",

"properties": {

"nom": {

"type": "string",

"minLength": 2

},

"age": {

"type": "number",

"minimum": 0,

"maximum": 120

},

"email": {

"type": "string",

"format": "email"

}

},

"required": ["nom", "email"]

}

\\\

Types de données

Types primitifs

\\\json

{

"type": "string" // Chaîne

"type": "number" // Nombre (int ou float)

"type": "integer" // Entier uniquement

"type": "boolean" // true ou false

"type": "null" // null

"type": "object" // Objet JSON

"type": "array" // Tableau

}

\\\

String

\\\json

{

"type": "string",

"minLength": 2,

"maxLength": 100,

"pattern": "^[A-Za-z]+$",

"format": "email" // email, uri, date-time, etc.

}

\\\

Formats courants :
  • date-time : "2026-01-16T10:00:00Z"
  • email : "user@example.com"
  • uri : "https://example.com"
  • ipv4 : "192.168.1.1"
  • uuid : "550e8400-e29b-41d4-a716-446655440000"

Number/Integer

\\\json

{

"type": "number",

"minimum": 0,

"maximum": 100,

"exclusiveMinimum": 0,

"exclusiveMaximum": 100,

"multipleOf": 0.01

}

\\\

Object

\\\json

{

"type": "object",

"properties": {

"nom": {"type": "string"},

"age": {"type": "number"}

},

"required": ["nom"],

"additionalProperties": false,

"minProperties": 1,

"maxProperties": 10

}

\\\

Array

\\\json

{

"type": "array",

"items": {

"type": "string"

},

"minItems": 1,

"maxItems": 10,

"uniqueItems": true

}

\\\

Contraintes de validation

Enum (valeurs fixes)

\\\json

{

"type": "string",

"enum": ["rouge", "vert", "bleu"]

}

\\\

Const (valeur unique)

\\\json

{

"type": "string",

"const": "production"

}

\\\

AllOf (toutes les conditions)

\\\json

{

"allOf": [

{"type": "object"},

{"properties": {"nom": {"type": "string"}}},

{"required": ["nom"]}

]

}

\\\

AnyOf (au moins une condition)

\\\json

{

"anyOf": [

{"type": "string"},

{"type": "number"}

]

}

\\\

OneOf (exactement une condition)

\\\json

{

"oneOf": [

{"type": "string", "maxLength": 5},

{"type": "number", "minimum": 0}

]

}

\\\

Not (négation)

\\\json

{

"not": {

"type": "null"

}

}

\\\

Schémas complexes

Objet imbriqué

\\\json

{

"$schema": "http://json-schema.org/draft-07/schema#",

"type": "object",

"properties": {

"utilisateur": {

"type": "object",

"properties": {

"nom": {"type": "string"},

"adresse": {

"type": "object",

"properties": {

"rue": {"type": "string"},

"ville": {"type": "string"},

"codePostal": {

"type": "string",

"pattern": "^[0-9]{5}$"

}

},

"required": ["ville", "codePostal"]

}

},

"required": ["nom"]

}

}

}

\\\

Tableau d'objets

\\\json

{

"type": "array",

"items": {

"type": "object",

"properties": {

"id": {"type": "integer"},

"nom": {"type": "string"}

},

"required": ["id", "nom"]

},

"minItems": 1

}

\\\

Références ($ref)

\\\json

{

"$schema": "http://json-schema.org/draft-07/schema#",

"definitions": {

"adresse": {

"type": "object",

"properties": {

"rue": {"type": "string"},

"ville": {"type": "string"}

}

}

},

"type": "object",

"properties": {

"adresseFacturation": {"$ref": "#/definitions/adresse"},

"adresseLivraison": {"$ref": "#/definitions/adresse"}

}

}

\\\

Validation en JavaScript

Avec Ajv

\\\javascript

// Installation: npm install ajv

import Ajv from 'ajv';

import addFormats from 'ajv-formats';

const ajv = new Ajv();

addFormats(ajv);

const schema = {

type: "object",

properties: {

nom: {type: "string", minLength: 2},

age: {type: "number", minimum: 0},

email: {type: "string", format: "email"}

},

required: ["nom", "email"]

};

const validate = ajv.compile(schema);

// Données valides

const data1 = {

nom: "Jean",

age: 30,

email: "jean@exemple.com"

};

if (validate(data1)) {

console.log("✓ Données valides");

} else {

console.log("✗ Erreurs:", validate.errors);

}

// Données invalides

const data2 = {

nom: "J", // Trop court

email: "invalide"

};

if (!validate(data2)) {

console.log("Erreurs:", validate.errors);

// [{instancePath: '/nom', message: 'must NOT have fewer than 2 characters'}, ...]

}

\\\

Validation en Python

Avec jsonschema

\\\python

# Installation: pip install jsonschema

from jsonschema import validate, ValidationError

import json

# Schéma

schema = {

"type": "object",

"properties": {

"nom": {"type": "string", "minLength": 2},

"age": {"type": "number", "minimum": 0},

"email": {"type": "string", "format": "email"}

},

"required": ["nom", "email"]

}

# Données valides

data_valid = {

"nom": "Jean",

"age": 30,

"email": "jean@exemple.com"

}

try:

validate(instance=data_valid, schema=schema)

print("✓ Données valides")

except ValidationError as e:

print(f"✗ Erreur: {e.message}")

# Données invalides

data_invalid = {

"nom": "J",

"email": "invalide"

}

try:

validate(instance=data_invalid, schema=schema)

except ValidationError as e:

print(f"✗ Erreur: {e.message}")

print(f"Chemin: {list(e.path)}")

\\\

Exemples pratiques

API utilisateur

\\\json

{

"$schema": "http://json-schema.org/draft-07/schema#",

"title": "Utilisateur",

"description": "Schéma pour créer un utilisateur",

"type": "object",

"properties": {

"nom": {

"type": "string",

"minLength": 2,

"maxLength": 50

},

"email": {

"type": "string",

"format": "email"

},

"age": {

"type": "integer",

"minimum": 18,

"maximum": 120

},

"role": {

"type": "string",

"enum": ["admin", "user", "guest"]

},

"actif": {

"type": "boolean",

"default": true

}

},

"required": ["nom", "email"]

}

\\\

Configuration application

\\\json

{

"$schema": "http://json-schema.org/draft-07/schema#",

"type": "object",

"properties": {

"database": {

"type": "object",

"properties": {

"host": {"type": "string"},

"port": {"type": "integer", "minimum": 1, "maximum": 65535},

"name": {"type": "string"}

},

"required": ["host", "port", "name"]

},

"cache": {

"type": "object",

"properties": {

"enabled": {"type": "boolean"},

"ttl": {"type": "integer", "minimum": 0}

}

}

},

"required": ["database"]

}

\\\

Outils et éditeurs

Online Schema Validators

  • jsonschemavalidator.net
  • jsonschemalint.com
  • extendsclass.com/json-schema-validator

Générateurs de schéma

  • quicktype.io
  • jsonschema.net
  • transform.tools/json-to-json-schema

Bonnes pratiques

  • Toujours inclure $schema
  • Utiliser descriptions
  • Définir required explicitement
  • Réutiliser avec $ref
  • Valider côté client ET serveur
  • Conclusion

    JSON Schema est essentiel pour :

    • Valider données API
    • Documenter structures
    • Générer code
    • Créer formulaires

    Points clés :
    • Support types riches
    • Contraintes flexibles
    • Réutilisation avec $ref
    • Validation cross-platform
    • Standards bien établis

    Share:

    Articles Connexes

    Read in English