JSON en JavaScript : JSON.parse, JSON.stringify et Manipulation de Données

JSON en JavaScript : JSON.parse, JSON.stringify et Manipulation de Données

Qu'est-ce que JSON ?

JSON (JavaScript Object Notation) est le format d'échange de données le plus utilisé sur le web. Léger, lisible par les humains et facilement parsable par les machines, il est devenu le standard pour les APIs REST, le stockage de configuration et la communication client-serveur.

Syntaxe JSON

{
    "nom": "Tourak Digital",
    "fondation": 2024,
    "services": ["Création web", "SEO", "Marketing digital"],
    "actif": true,
    "adresse": {
        "ville": "Troyes",
        "pays": "France"
    },
    "note": null
}

Règles de syntaxe JSON

  • Les clés doivent être des chaînes entre guillemets doubles (pas de simples quotes)
  • Les valeurs peuvent être : string, number, boolean, null, array, object
  • Pas de virgule finale (trailing comma)
  • Pas de commentaires
  • Pas de fonctions, undefined, NaN, Infinity, -Infinity, Date, RegExp

JSON.parse() : convertir du JSON en objet JavaScript

// Usage basique
const jsonString = '{"nom": "Tourak", "services": ["Web", "SEO"]}';
const obj = JSON.parse(jsonString);
console.log(obj.nom);      // "Tourak"
console.log(obj.services);  // ["Web", "SEO"]

// Avec gestion d'erreur (INDISPENSABLE)
function safeJsonParse(str) {
    try {
        return JSON.parse(str);
    } catch (error) {
        console.error('JSON invalide:', error.message);
        return null;
    }
}

// Exemple avec des données de l'API
const response = await fetch('/api/data');
const text = await response.text();
const data = safeJsonParse(text);
if (data) {
    // Traitement des données
}

Le paramètre reviver de JSON.parse()

// Le reviver transforme les valeurs pendant le parsing
const json = '{"nom": "Test", "date": "2026-03-18T10:00:00Z", "prix": "29.99"}';

const obj = JSON.parse(json, (key, value) => {
    // Convertir automatiquement les dates
    if (key === 'date') return new Date(value);
    // Convertir les prix en nombre
    if (key === 'prix') return parseFloat(value);
    return value;
});

console.log(obj.date instanceof Date); // true
console.log(typeof obj.prix);         // "number"

JSON.stringify() : convertir un objet en JSON

const obj = {
    nom: "Tourak Digital",
    services: ["Création web", "SEO"],
    actif: true
};

// Basique
const json = JSON.stringify(obj);
// '{"nom":"Tourak Digital","services":["Création web","SEO"],"actif":true}'

// Avec indentation (pour la lisibilité)
const jsonPretty = JSON.stringify(obj, null, 2);
/*
{
  "nom": "Tourak Digital",
  "services": [
    "Création web",
    "SEO"
  ],
  "actif": true
}
*/

// Avec indentation tab
const jsonTab = JSON.stringify(obj, null, '\t');

Le paramètre replacer de JSON.stringify()

// Filtrer les propriétés avec un tableau
const user = { nom: "Jean", email: "jean@mail.com", motDePasse: "secret123" };

const json = JSON.stringify(user, ['nom', 'email']);
// '{"nom":"Jean","email":"jean@mail.com"}' - motDePasse exclu !

// Transformer les valeurs avec une fonction
const json2 = JSON.stringify(user, (key, value) => {
    if (key === 'motDePasse') return undefined; // Exclure
    if (key === 'email') return value.toLowerCase(); // Transformer
    return value;
});

// La méthode toJSON() sur les objets
class Utilisateur {
    constructor(nom, email, mdp) {
        this.nom = nom;
        this.email = email;
        this.motDePasse = mdp;
    }

    toJSON() {
        return { nom: this.nom, email: this.email };
        // motDePasse automatiquement exclu
    }
}

const u = new Utilisateur('Jean', 'jean@mail.com', 'secret');
JSON.stringify(u); // '{"nom":"Jean","email":"jean@mail.com"}'

Cas d'usage courants

localStorage avec JSON

// Sauvegarder un objet dans localStorage
const settings = { theme: 'dark', lang: 'fr', fontSize: 16 };
localStorage.setItem('settings', JSON.stringify(settings));

// Récupérer un objet depuis localStorage
const saved = JSON.parse(localStorage.getItem('settings'));
if (saved) {
    applySettings(saved);
}

// Avec valeur par défaut
function getFromStorage(key, defaultValue) {
    try {
        const item = localStorage.getItem(key);
        return item ? JSON.parse(item) : defaultValue;
    } catch {
        return defaultValue;
    }
}

Clonage profond d'objets

// Clonage profond rapide (avec limitations)
const original = { a: 1, b: { c: 2 }, d: [3, 4] };
const clone = JSON.parse(JSON.stringify(original));

clone.b.c = 99; // Ne modifie PAS original.b.c

// ATTENTION : limitations
// - Perd les fonctions, undefined, Symbol
// - Ne gère pas les références circulaires
// - Convertit les Date en string, Map/Set en {}

// Alternative moderne (2026) : structuredClone
const cloneModerne = structuredClone(original);
// Gère Date, Map, Set, ArrayBuffer, etc.

Comparaison d'objets

// Comparer deux objets par leur contenu
function deepEqual(a, b) {
    return JSON.stringify(a) === JSON.stringify(b);
}

// ATTENTION : l'ordre des clés compte
deepEqual({a:1, b:2}, {b:2, a:1}); // false !

// Version robuste avec tri des clés
function sortedStringify(obj) {
    return JSON.stringify(obj, Object.keys(obj).sort());
}

Validation de JSON

function isValidJSON(str) {
    try {
        JSON.parse(str);
        return true;
    } catch {
        return false;
    }
}

// Validation avec schéma (structure attendue)
function validateUserJSON(json) {
    const data = JSON.parse(json);
    const required = ['nom', 'email'];
    const missing = required.filter(key => !(key in data));
    if (missing.length > 0) {
        throw new Error(`Champs manquants: ${missing.join(', ')}`);
    }
    return data;
}

Valeurs problématiques avec JSON

Valeur JavaScriptRésultat JSON.stringifySolution
undefinedOmis (clé supprimée)Utiliser null
NaNnullVérifier avant
InfinitynullConvertir en string
DateString ISOReviver pour reconvertir
Map / Set{} / undefinedConvertir en Array
RegExp{}Convertir en string
FunctionOmisNe pas inclure
Référence circulaireTypeErrorBibliothèque spécialisée

JSON et les APIs : bonnes pratiques

// Client API avec gestion JSON robuste
async function apiRequest(endpoint, options = {}) {
    const config = {
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            ...options.headers
        },
        ...options
    };

    if (config.body && typeof config.body === 'object') {
        config.body = JSON.stringify(config.body);
    }

    const response = await fetch(endpoint, config);
    const contentType = response.headers.get('Content-Type');

    let data;
    if (contentType && contentType.includes('application/json')) {
        data = await response.json();
    } else {
        data = await response.text();
    }

    if (!response.ok) {
        throw { status: response.status, data };
    }

    return data;
}

Conclusion

JSON est le langage universel de l'échange de données web. Maîtriser JSON.parse() et JSON.stringify() avec leurs options avancées (reviver, replacer) est essentiel pour tout développeur JavaScript. N'oubliez jamais de gérer les erreurs de parsing et de valider les données entrantes.

Chez Tourak Digital, nous construisons des applications web robustes avec une gestion rigoureuse des données. Confiez-nous votre projet.

SEO Création Web Google Ads Marketing Blog À propos
Liens rapides
Informations
Tourak Digital Group