← Retour au Blog

Guide complet JSON Beautifier : Embellir et formater votre JSON

Maîtrisez les JSON beautifiers pour améliorer la lisibilité de vos données. Outils, techniques et meilleures pratiques pour un JSON parfaitement formaté.

Big JSON Team12 min de lecturetools
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.

12 min de lecture

# Guide complet JSON Beautifier : Embellir et formater votre JSON

Un JSON beautifier transforme du JSON compact et illisible en un format propre et structuré. Ce guide explore tous les aspects des JSON beautifiers.

Qu'est-ce qu'un JSON Beautifier ?

Un JSON beautifier (ou prettifier) est un outil qui formate automatiquement le code JSON pour le rendre plus lisible en ajoutant :

  • Indentation cohérente
  • Espaces appropriés
  • Sauts de ligne logiques
  • Structure visuelle claire

Avant beautification

\\\json

{"utilisateur":{"id":1,"nom":"Jean Dupont","email":"jean@exemple.com","adresse":{"rue":"123 Rue Principale","ville":"Paris","codePostal":"75001"},"roles":["admin","utilisateur"],"preferences":{"theme":"sombre","langue":"fr","notifications":true}}}

\\\

Après beautification

\\\json

{

"utilisateur": {

"id": 1,

"nom": "Jean Dupont",

"email": "jean@exemple.com",

"adresse": {

"rue": "123 Rue Principale",

"ville": "Paris",

"codePostal": "75001"

},

"roles": [

"admin",

"utilisateur"

],

"preferences": {

"theme": "sombre",

"langue": "fr",

"notifications": true

}

}

}

\\\

Pourquoi utiliser un JSON Beautifier ?

1. Lisibilité améliorée

JSON minifié :

\\\json

{"produits":[{"id":"P001","nom":"Laptop","prix":999,"stock":{"quantite":45,"entrepot":"A"}},{"id":"P002","nom":"Souris","prix":25,"stock":{"quantite":150,"entrepot":"B"}}]}

\\\

JSON embelli :

\\\json

{

"produits": [

{

"id": "P001",

"nom": "Laptop",

"prix": 999,

"stock": {

"quantite": 45,

"entrepot": "A"

}

},

{

"id": "P002",

"nom": "Souris",

"prix": 25,

"stock": {

"quantite": 150,

"entrepot": "B"

}

}

]

}

\\\

2. Débogage facilité

Identifiez rapidement les erreurs et la structure des données.

3. Collaboration d'équipe

Code plus maintenable et compréhensible par tous.

4. Révision de code

Facilite la relecture et la validation.

JSON Beautifiers en JavaScript

Méthode native : JSON.stringify()

\\\javascript

// JSON minifié

const donnees = {

nom: "Jean",

age: 30,

ville: "Paris",

competences: ["JavaScript", "Python", "SQL"]

};

// Beautify avec 2 espaces d'indentation

const jsonEmbelli = JSON.stringify(donnees, null, 2);

console.log(jsonEmbelli);

/

{

"nom": "Jean",

"age": 30,

"ville": "Paris",

"competences": [

"JavaScript",

"Python",

"SQL"

]

}

/

// Avec 4 espaces

const jsonEmbelli4 = JSON.stringify(donnees, null, 4);

// Avec tabulation (non recommandé)

const jsonEmbelliTab = JSON.stringify(donnees, null, '\t');

\\\

Beautifier personnalisé avec filtrage

\\\javascript

const utilisateur = {

nom: "Jean",

age: 30,

motDePasse: "secret123",

email: "jean@exemple.com",

cleAPI: "sk_live_abc123xyz"

};

// Beautify en masquant les données sensibles

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

// Masquer les champs sensibles

const champsSecrets = ['motDePasse', 'cleAPI'];

if (champsSecrets.includes(cle)) {

return 'MASQUÉ';

}

return valeur;

}, 2);

console.log(jsonSecurise);

/

{

"nom": "Jean",

"age": 30,

"motDePasse": "MASQUÉ",

"email": "jean@exemple.com",

"cleAPI": "MASQUÉ"

}

/

\\\

Beautifier avec tri des clés

\\\javascript

function beautifyAvecTri(obj, espace = 2) {

return JSON.stringify(obj, (cle, valeur) => {

// Trier uniquement les objets (pas les tableaux)

if (valeur && typeof valeur === 'object' && !Array.isArray(valeur)) {

return Object.keys(valeur)

.sort()

.reduce((resultat, k) => {

resultat[k] = valeur[k];

return resultat;

}, {});

}

return valeur;

}, espace);

}

const donnees = {

z_dernier: 1,

a_premier: 2,

m_milieu: 3,

b_deuxieme: 4

};

console.log(beautifyAvecTri(donnees));

/

{

"a_premier": 2,

"b_deuxieme": 4,

"m_milieu": 3,

"z_dernier": 1

}

/

\\\

JSON Beautifiers en Python

Module json intégré

\\\python

import json

# Données

donnees = {

"nom": "Jean",

"age": 30,

"ville": "Paris",

"competences": ["JavaScript", "Python", "SQL"]

}

# Beautify avec indentation de 2 espaces

json_embelli = json.dumps(donnees, indent=2, ensure_ascii=False)

print(json_embelli)

# Options avancées

json_complet = json.dumps(

donnees,

indent=4, # Indentation 4 espaces

sort_keys=True, # Trier les clés

ensure_ascii=False, # Supporter Unicode

separators=(', ', ': ') # Séparateurs personnalisés

)

print(json_complet)

\\\

Beautifier depuis fichier

\\\python

import json

# Lire et beautifier un fichier JSON

def beautifier_fichier(fichier_entree, fichier_sortie, indent=2):

with open(fichier_entree, 'r', encoding='utf-8') as f:

donnees = json.load(f)

with open(fichier_sortie, 'w', encoding='utf-8') as f:

json.dump(donnees, f, indent=indent, ensure_ascii=False)

# Utilisation

beautifier_fichier('donnees.json', 'donnees_embellies.json')

\\\

Beautifiers en ligne de commande

jq (Puissant et flexible)

\\\bash

# Installation

MacOS

brew install jq

Linux (Ubuntu/Debian)

sudo apt-get install jq

Windows

choco install jq

# Beautify simple

jq . fichier.json

# Avec indentation personnalisée (4 espaces)

jq --indent 4 . fichier.json

# Beautify et trier les clés

jq -S . fichier.json

# Beautify et sauvegarder

jq . fichier.json > fichier_embelli.json

# Beautify depuis stdin

echo '{"nom":"Jean","age":30}' | jq .

# Beautify avec couleurs

jq -C . fichier.json

# Minifier (inverse de beautify)

jq -c . fichier.json

\\\

Python (ligne de commande)

\\\bash

# Beautify avec Python

python -m json.tool fichier.json

# Sauvegarder dans nouveau fichier

python -m json.tool fichier.json fichier_embelli.json

# Avec tri des clés

python -m json.tool --sort-keys fichier.json

# Depuis stdin

echo '{"nom":"Jean","age":30}' | python -m json.tool

\\\

Node.js

\\\bash

# Beautify inline

node -e "console.log(JSON.stringify(require('./fichier.json'), null, 2))"

# Créer un script beautifier.js

cat > beautifier.js << 'EOF'

const fs = require('fs');

const data = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));

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

EOF

# Utiliser le script

node beautifier.js fichier.json > fichier_embelli.json

\\\

Beautifiers dans les éditeurs

Visual Studio Code

Raccourcis :
  • Windows/Linux : Shift + Alt + F
  • Mac : Shift + Option + F
  • Tous : Clic droit → "Format Document"

Configuration automatique (settings.json) :

\\\json

{

"editor.formatOnSave": true,

"editor.defaultFormatter": "vscode.json-language-features",

"[json]": {

"editor.tabSize": 2,

"editor.insertSpaces": true,

"editor.detectIndentation": false

},

"json.format.enable": true,

"json.format.keepLines": false

}

\\\

Extensions recommandées :
  • Prettier : Formatage avancé
  • JSON Tools : Outils supplémentaires
  • Sort JSON objects : Tri des clés

Sublime Text

Package : Pretty JSON

\\\bash

# Installation via Package Control

Cmd/Ctrl + Shift + P → Install Package → Pretty JSON

\\\

Raccourcis :
  • Beautify : Cmd/Ctrl + Alt + J
  • Minify : Cmd/Ctrl + Alt + M
  • Validate : Cmd/Ctrl + Alt + V

Atom

Package : pretty-json

\\\bash

apm install pretty-json

\\\

Raccourci : Cmd/Ctrl + Alt + P

IntelliJ IDEA / WebStorm

Raccourci format :
  • Windows/Linux : Ctrl + Alt + L
  • Mac : Cmd + Option + L

Beautifiers en ligne

1. JSONLint

  • URL : jsonlint.com
  • Validation + beautification
  • Simple et rapide

2. JSON Formatter

  • URL : jsonformatter.org
  • Interface claire
  • Options multiples

3. Code Beautify

  • URL : codebeautify.org/jsonviewer
  • Multi-outils
  • Gratuit

4. FreeFormatter

  • URL : www.freeformatter.com/json-formatter.html
  • Options avancées
  • Pas de publicité intrusive

Bibliothèques JavaScript

Prettier (Recommandé)

\\\bash

npm install --save-dev prettier

\\\

\\\javascript

const prettier = require('prettier');

const jsonMinifie = '{"nom":"Jean","age":30}';

const jsonEmbelli = prettier.format(jsonMinifie, {

parser: 'json',

tabWidth: 2,

useTabs: false,

semi: true,

singleQuote: false

});

console.log(jsonEmbelli);

\\\

Configuration (.prettierrc) :

\\\json

{

"tabWidth": 2,

"useTabs": false,

"trailingComma": "none",

"printWidth": 80

}

\\\

json-beautify

\\\bash

npm install json-beautify

\\\

\\\javascript

const beautify = require('json-beautify');

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

const resultat = beautify(donnees, null, 2, 80);

console.log(resultat);

\\\

Options de beautification

1. Niveau d'indentation

2 espaces (recommandé web) :

\\\json

{

"nom": "Jean",

"age": 30

}

\\\

4 espaces (recommandé général) :

\\\json

{

"nom": "Jean",

"age": 30

}

\\\

2. Gestion des tableaux

Tableaux courts inline :

\\\json

{

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

}

\\\

Tableaux longs multi-lignes :

\\\json

{

"utilisateurs": [

{"id": 1, "nom": "Alice"},

{"id": 2, "nom": "Bob"},

{"id": 3, "nom": "Charlie"}

]

}

\\\

3. Tri des clés

Non trié (ordre d'origine) :

\\\json

{

"z": 1,

"a": 2,

"m": 3

}

\\\

Trié alphabétiquement :

\\\json

{

"a": 2,

"m": 3,

"z": 1

}

\\\

Automatisation

NPM Scripts

package.json :

\\\json

{

"scripts": {

"beautify": "prettier --write '*/.json'",

"beautify:check": "prettier --check '*/.json'",

"beautify:specific": "prettier --write src/config/.json"

},

"devDependencies": {

"prettier": "^3.0.0"

}

}

\\\

\\\bash

# Beautifier tous les JSON

npm run beautify

# Vérifier sans modifier

npm run beautify:check

\\\

Git Pre-commit Hook

\\\bash

#!/bin/bash

# .git/hooks/pre-commit

# Beautifier les fichiers JSON modifiés

for file in $(git diff --cached --name-only | grep '\.json$'); do

# Utiliser jq pour beautifier

jq . "$file" > "$file.tmp" && mv "$file.tmp" "$file"

# Ou utiliser prettier

# prettier --write "$file"

git add "$file"

done

\\\

GitHub Actions

\\\yaml

# .github/workflows/beautify-json.yml

name: Beautify JSON

on: [push, pull_request]

jobs:

beautify:

runs-on: ubuntu-latest

steps:

- uses: actions/checkout@v3

- uses: actions/setup-node@v3

with:

node-version: '18'

- run: npm install -g prettier

- run: prettier --check '/.json'

\\\

Meilleures pratiques

1. Cohérence

Utilisez toujours le même style :

  • Même indentation dans tout le projet
  • Même convention de tri
  • Même gestion des tableaux

2. Automatisation

Configurez l'auto-formatage :

  • Format on save dans l'éditeur
  • Pre-commit hooks
  • CI/CD validation

3. Documentation

Documentez vos conventions :

\\\markdown

Standards JSON

  • Indentation : 2 espaces
  • Pas de tabulations
  • Tri des clés : alphabétique pour config
  • Tableaux < 3 éléments : inline
\
\\

4. Performance

Pour gros fichiers :

  • Utilisez jq (plus rapide)
  • Évitez les outils en ligne
  • Stream processing si possible

Pièges à éviter

1. Ne pas perdre les données

Toujours sauvegarder avant beautification massive :

\\\bash

# Backup avant modification

cp fichier.json fichier.json.backup

jq . fichier.json > fichier.json.tmp && mv fichier.json.tmp fichier.json

\\\

2. Encodage

Préservez l'encodage UTF-8 :

\\\javascript

// Mauvais : perd les caractères spéciaux

JSON.stringify(donnees, null, 2)

// Bon : préserve UTF-8

const fs = require('fs');

fs.writeFileSync('fichier.json',

JSON.stringify(donnees, null, 2),

'utf8'

);

\\\

3. Données sensibles

Ne pas beautifier/copier les données sensibles en ligne.

Conclusion

Beautifiers recommandés : Pour développement quotidien :
  • VS Code avec Prettier
  • Format on save activé

Pour ligne de commande :
  • jq (le plus puissant)
  • Python json.tool (portable)

Pour en ligne (données non-sensibles) :
  • JSONLint (validation + beautify)
  • JSON Formatter (options multiples)

Points clés :
  • Automatisez le formatage
  • Établissez des standards d'équipe
  • Utilisez des outils locaux pour données sensibles
  • Configurez votre éditeur correctement
  • Intégrez dans votre workflow CI/CD
  • Avec un JSON beautifier approprié, votre code sera toujours propre, lisible et professionnel !

    Share:

    Articles Connexes

    Read in English