Definition
JSON (JavaScript Object Notation) est un format de donnees textuel leger, lisible par les humains et facile a parser par les machines. C'est le format d'echange standard pour les API web, les fichiers de configuration et le stockage de donnees structurees.
Bien que derive de JavaScript, JSON est un format independant du langage, supporte par tous les langages de programmation modernes.
Syntaxe
{
"nom": "Alice Dupont",
"age": 30,
"email": "alice@exemple.com",
"actif": true,
"adresse": {
"rue": "123 rue de la Paix",
"ville": "Paris",
"cp": "75001"
},
"langages": ["Python", "JavaScript", "Go"],
"manager": null
}
Types de donnees JSON
| Type | Exemple | Equivalent JavaScript |
|---|---|---|
| String | "hello" |
string |
| Number | 42, 3.14 |
number |
| Boolean | true, false |
boolean |
| Array | [1, 2, 3] |
Array |
| Object | {"key": "value"} |
Object |
| null | null |
null |
Attention : JSON ne supporte pas les commentaires, les dates (utilisez des strings ISO 8601), ni les valeurs undefined ou NaN.
Manipulation en JavaScript
// Objet → JSON string
const json = JSON.stringify({ nom: "Alice", age: 30 });
// '{"nom":"Alice","age":30}'
// JSON string → Objet
const obj = JSON.parse('{"nom":"Alice","age":30}');
// { nom: "Alice", age: 30 }
// Pretty print
JSON.stringify(data, null, 2);
JSON dans les API
// Requete API avec JSON
const response = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ nom: 'Alice', email: 'alice@exemple.com' }),
});
const data = await response.json();
JSON Schema
JSON Schema permet de valider la structure d'un document JSON :
{
"type": "object",
"required": ["nom", "email"],
"properties": {
"nom": { "type": "string", "minLength": 1 },
"email": { "type": "string", "format": "email" },
"age": { "type": "integer", "minimum": 0 }
}
}
Alternatives a JSON
| Format | Avantage | Cas d'usage |
|---|---|---|
| YAML | Plus lisible, commentaires | Configuration |
| TOML | Simple, sections | Configuration (Rust, Go) |
| Protocol Buffers | Binaire, performant, type | gRPC, communication inter-services |
| MessagePack | JSON binaire, compact | Cache, stockage compact |
| XML | Schema strict, namespaces | Enterprise, SOAP |