← Retour au Blog

JavaScript et JSON : Guide complet de manipulation des données

Maîtrisez JSON en JavaScript avec JSON.parse(), JSON.stringify(), et techniques avancées. Guide pratique avec exemples pour le développement web moderne.

Big JSON Team13 min de lectureprogramming
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.

13 min de lecture

# JavaScript et JSON : Guide complet de manipulation des données

JavaScript et JSON sont naturellement liés. Ce guide complet vous apprend à maîtriser JSON en JavaScript pour le développement web moderne.

JSON en JavaScript natif

JSON.parse() - Convertir JSON en objet JavaScript

\\\javascript

// Chaîne JSON

const jsonString = '{"nom":"Jean","age":30,"ville":"Paris"}';

// Parser en objet JavaScript

const utilisateur = JSON.parse(jsonString);

console.log(utilisateur.nom); // "Jean"

console.log(utilisateur.age); // 30

console.log(typeof utilisateur); // "object"

\\\

JSON.stringify() - Convertir objet en JSON

\\\javascript

// Objet JavaScript

const utilisateur = {

nom: "Jean Dupont",

age: 30,

ville: "Paris",

actif: true

};

// Convertir en JSON

const jsonString = JSON.stringify(utilisateur);

console.log(jsonString);

// {"nom":"Jean Dupont","age":30,"ville":"Paris","actif":true}

// Avec indentation

const jsonFormate = JSON.stringify(utilisateur, null, 2);

console.log(jsonFormate);

/

{

"nom": "Jean Dupont",

"age": 30,

"ville": "Paris",

"actif": true

}

/

\\\

Conversion des types

JavaScript → JSON

\\\javascript

const donnees = {

chaine: "Bonjour",

nombre: 42,

decimal: 3.14,

booleen: true,

nul: null,

tableau: [1, 2, 3],

objet: {cle: "valeur"},

date: new Date(), // Converti en string ISO

undefined: undefined, // Omis

fonction: () => {}, // Omis

symbol: Symbol("test") // Omis

};

console.log(JSON.stringify(donnees, null, 2));

/

{

"chaine": "Bonjour",

"nombre": 42,

"decimal": 3.14,

"booleen": true,

"nul": null,

"tableau": [1, 2, 3],

"objet": {"cle": "valeur"},

"date": "2026-01-16T10:30:00.000Z"

}

/

\\\

Options avancées de JSON.stringify()

Paramètre replacer (filtre)

\\\javascript

const utilisateur = {

nom: "Jean",

age: 30,

motDePasse: "secret123",

email: "jean@exemple.com"

};

// Tableau de clés à inclure

const json1 = JSON.stringify(utilisateur, ["nom", "email"]);

console.log(json1);

// {"nom":"Jean","email":"jean@exemple.com"}

// Fonction de filtrage

const json2 = JSON.stringify(utilisateur, (cle, valeur) => {

// Masquer le mot de passe

if (cle === "motDePasse") {

return "";

}

return valeur;

});

console.log(json2);

// {"nom":"Jean","age":30,"motDePasse":"","email":"jean@exemple.com"}

\\\

Méthode toJSON()

\\\javascript

class Utilisateur {

constructor(nom, age, motDePasse) {

this.nom = nom;

this.age = age;

this.motDePasse = motDePasse;

}

toJSON() {

// Contrôler la serialization

return {

nom: this.nom,

age: this.age

// motDePasse exclu

};

}

}

const user = new Utilisateur("Jean", 30, "secret");

console.log(JSON.stringify(user));

// {"nom":"Jean","age":30}

\\\

Options avancées de JSON.parse()

Paramètre reviver (transformation)

\\\javascript

const jsonString = '{"nom":"Jean","dateCreation":"2026-01-16T10:00:00Z","age":30}';

// Parser avec transformation

const donnees = JSON.parse(jsonString, (cle, valeur) => {

// Convertir les dates ISO en objets Date

if (cle === "dateCreation") {

return new Date(valeur);

}

return valeur;

});

console.log(donnees.dateCreation instanceof Date); // true

console.log(donnees.dateCreation.getFullYear()); // 2026

\\\

Travailler avec les API

Fetch API avec JSON

\\\javascript

// GET request

async function obtenirUtilisateur(id) {

try {

const response = await fetch(\https://api.exemple.com/users/${id}\);

if (!response.ok) {

throw new Error(\HTTP error! status: ${response.status}\);

}

const utilisateur = await response.json(); // Parse automatique

return utilisateur;

} catch (erreur) {

console.error("Erreur:", erreur);

}

}

// Utilisation

obtenirUtilisateur(123).then(user => {

console.log(user.nom);

});

\\\

POST avec JSON

\\\javascript

async function creerUtilisateur(donnees) {

try {

const response = await fetch('https://api.exemple.com/users', {

method: 'POST',

headers: {

'Content-Type': 'application/json'

},

body: JSON.stringify(donnees) // Convertir en JSON

});

const resultat = await response.json();

return resultat;

} catch (erreur) {

console.error("Erreur:", erreur);

}

}

// Utilisation

creerUtilisateur({

nom: "Jean Dupont",

email: "jean@exemple.com"

}).then(user => console.log(user));

\\\

LocalStorage et SessionStorage

Sauvegarder objets dans localStorage

\\\javascript

// Sauvegarder

const utilisateur = {

nom: "Jean",

preferences: {

theme: "sombre",

langue: "fr"

}

};

localStorage.setItem('utilisateur', JSON.stringify(utilisateur));

// Récupérer

const utilisateurSauvegarde = JSON.parse(

localStorage.getItem('utilisateur')

);

console.log(utilisateurSauvegarde.preferences.theme); // "sombre"

\\\

Helper functions

\\\javascript

const storage = {

set(cle, valeur) {

localStorage.setItem(cle, JSON.stringify(valeur));

},

get(cle) {

const item = localStorage.getItem(cle);

return item ? JSON.parse(item) : null;

},

remove(cle) {

localStorage.removeItem(cle);

}

};

// Utilisation

storage.set('config', {theme: 'sombre', langue: 'fr'});

const config = storage.get('config');

console.log(config.theme); // "sombre"

\\\

Gestion des erreurs

Try-catch pour JSON.parse()

\\\javascript

function parseSafe(jsonString) {

try {

return JSON.parse(jsonString);

} catch (erreur) {

console.error("Erreur de parsing JSON:", erreur.message);

return null;

}

}

// Test avec JSON invalide

const result = parseSafe('{"nom": "Jean",}'); // Virgule finale

// Erreur de parsing JSON: Unexpected token } in JSON at position 15

console.log(result); // null

\\\

Validation JSON

\\\javascript

function estJSONValide(str) {

try {

JSON.parse(str);

return true;

} catch (e) {

return false;

}

}

console.log(estJSONValide('{"nom":"Jean"}')); // true

console.log(estJSONValide('{"nom":"Jean",}')); // false

console.log(estJSONValide("{'nom':'Jean'}")); // false

\\\

Deep Clone avec JSON

\\\javascript

const original = {

nom: "Jean",

adresse: {

ville: "Paris",

code: "75001"

},

hobbies: ["lecture", "sport"]

};

// Clone profond

const clone = JSON.parse(JSON.stringify(original));

// Modifier le clone n'affecte pas l'original

clone.adresse.ville = "Lyon";

clone.hobbies.push("musique");

console.log(original.adresse.ville); // "Paris" (inchangé)

console.log(clone.adresse.ville); // "Lyon"

// ⚠️ Limitations: perd les fonctions, Date, undefined, etc.

\\\

Formatage et Pretty Print

\\\javascript

const donnees = {

utilisateur: {

nom: "Jean",

competences: ["JS", "Python"]

}

};

// Indentation 2 espaces

console.log(JSON.stringify(donnees, null, 2));

// Indentation 4 espaces

console.log(JSON.stringify(donnees, null, 4));

// Tabulation (non recommandé)

console.log(JSON.stringify(donnees, null, '\t'));

\\\

Manipulation JSON avancée

Fusionner objets JSON

\\\javascript

const base = {

nom: "Jean",

age: 30,

ville: "Paris"

};

const mise_a_jour = {

age: 31,

email: "jean@exemple.com"

};

// Fusion simple

const fusion = {...base, ...mise_a_jour};

console.log(fusion);

// {nom: "Jean", age: 31, ville: "Paris", email: "jean@exemple.com"}

// Fusion profonde

function fusionProfonde(obj1, obj2) {

return JSON.parse(

JSON.stringify({...obj1, ...obj2})

);

}

\\\

Filtrer propriétés

\\\javascript

const utilisateur = {

id: 1,

nom: "Jean",

age: 30,

motDePasse: "secret",

email: "jean@exemple.com"

};

// Exclure certaines clés

function excludeKeys(obj, keys) {

return JSON.parse(

JSON.stringify(obj, (k, v) =>

keys.includes(k) ? undefined : v

)

);

}

const public = excludeKeys(utilisateur, ['motDePasse']);

console.log(public);

// {id: 1, nom: "Jean", age: 30, email: "jean@exemple.com"}

\\\

JSON dans le DOM

Data attributes

\\\html

\\\

\\\javascript

// JavaScript

const card = document.getElementById('user-card');

const userData = JSON.parse(card.dataset.user);

console.log(userData.nom); // "Jean"

\\\

Script tag pour configuration

\\\html

\\\

\\\javascript

// JavaScript

const configElement = document.getElementById('config');

const config = JSON.parse(configElement.textContent);

console.log(config.apiUrl);

\\\

Performance et optimisation

Minification

\\\javascript

const donnees = {nom: "Jean", age: 30, ville: "Paris"};

// JSON minifié (pour transfert réseau)

const minified = JSON.stringify(donnees);

console.log(minified);

// {"nom":"Jean","age":30,"ville":"Paris"}

// Taille réduite sans espaces

console.log(minified.length); // Plus petit

\\\

Streaming pour gros JSON

\\\javascript

// Pour très gros fichiers JSON

async function* streamJSON(url) {

const response = await fetch(url);

const reader = response.body.getReader();

const decoder = new TextDecoder();

let buffer = '';

while (true) {

const {done, value} = await reader.read();

if (done) break;

buffer += decoder.decode(value, {stream: true});

// Traiter ligne par ligne (JSON Lines format)

const lines = buffer.split('\n');

buffer = lines.pop(); // Garder dernière ligne incomplète

for (const line of lines) {

if (line.trim()) {

yield JSON.parse(line);

}

}

}

}

// Utilisation

for await (const obj of streamJSON('large-data.jsonl')) {

console.log(obj);

}

\\\

Bonnes pratiques

1. Toujours valider les entrées

\\\javascript

function parseJSONSafe(str, defaultValue = null) {

if (typeof str !== 'string') {

return defaultValue;

}

try {

return JSON.parse(str);

} catch (e) {

console.error('JSON parse error:', e);

return defaultValue;

}

}

\\\

2. Ne pas stocker de données sensibles

\\\javascript

// ❌ Mauvais

const user = {

nom: "Jean",

motDePasse: "secret123",

cleAPI: "sk_live_abc"

};

localStorage.setItem('user', JSON.stringify(user));

// ✅ Bon

const user = {

nom: "Jean",

id: 123

};

// Garder données sensibles côté serveur

\\\

3. Utiliser TypeScript pour la sécurité de type

\\\typescript

interface Utilisateur {

nom: string;

age: number;

email: string;

}

function parseUtilisateur(json: string): Utilisateur | null {

try {

const data = JSON.parse(json);

// Valider la structure

if (typeof data.nom === 'string' &&

typeof data.age === 'number' &&

typeof data.email === 'string') {

return data as Utilisateur;

}

return null;

} catch {

return null;

}

}

\\\

Conclusion

Méthodes clés JavaScript-JSON :
  • JSON.parse() : JSON → Objet
  • JSON.stringify() : Objet → JSON
  • Paramètres replacer et reviver pour contrôle fin
  • response.json() pour Fetch API

Points essentiels :
  • Toujours gérer les erreurs avec try-catch
  • Utiliser replacer pour filtrer données sensibles
  • Valider les données avant utilisation
  • Minifier pour transfert réseau
  • Formater pour développement (indent)
  • Maîtrisez ces techniques et vous manipulerez JSON parfaitement en JavaScript !

    Share:

    Articles Connexes

    Read in English