← Zurück zum Blog

JSON formatieren: Vollständige Anleitung mit Tools und Techniken

Lernen Sie, wie Sie JSON-Daten richtig formatieren. Praktische Anleitungen, Tools, Code-Beispiele und Best Practices für lesbares JSON.

Big JSON Team11 Min. Lesezeittools
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.

11 Min. Lesezeit

# JSON formatieren: Vollständige Anleitung

Ein umfassender Leitfaden zum Formatieren von JSON-Daten für bessere Lesbarkeit und Wartbarkeit.

Was ist JSON-Formatierung?

JSON-Formatierung (auch "Pretty Print" oder "Beautify" genannt) ist der Prozess, bei dem JSON-Daten mit korrekter Einrückung, Zeilenumbrüchen und Leerzeichen versehen werden, um sie lesbarer zu machen.

Unformatiertes JSON

{"name":"Max Mustermann","alter":30,"adresse":{"straße":"Hauptstraße 1","stadt":"Berlin","plz":"10115"},"hobbys":["Programmieren","Musik","Sport"]}

Formatiertes JSON

{

"name": "Max Mustermann",

"alter": 30,

"adresse": {

"straße": "Hauptstraße 1",

"stadt": "Berlin",

"plz": "10115"

},

"hobbys": [

"Programmieren",

"Musik",

"Sport"

]

}

Warum JSON formatieren?

1. Bessere Lesbarkeit

Formatiertes JSON ist viel einfacher zu lesen und zu verstehen:

// Schwer zu lesen

{"benutzer":{"id":1,"name":"Max","emails":["max@work.de","max@home.de"],"aktiv":true}}

// Leicht zu lesen

{

"benutzer": {

"id": 1,

"name": "Max",

"emails": [

"max@work.de",

"max@home.de"

],

"aktiv": true

}

}

2. Einfacheres Debugging

Fehler sind leichter zu finden:

{

"name": "Max",

"alter": 30,

"stadt": "Berlin", // ← Fehler hier: Komma am Ende!

}

3. Bessere Versionskontrolle

Git-Diffs sind aussagekräftiger bei formatiertem JSON.

4. Professionelle Präsentation

Formatierter Code wirkt professioneller und ist wartungsfreundlicher.

JSON mit Code formatieren

JavaScript/Node.js

JSON.stringify() mit Formatierung

const daten = {

name: "Max Mustermann",

alter: 30,

adresse: {

stadt: "Berlin",

plz: "10115"

}

};

// Grundlegende Formatierung (2 Leerzeichen Einrückung)

const formatiert = JSON.stringify(daten, null, 2);

console.log(formatiert);

// Mit 4 Leerzeichen

const formatiert4 = JSON.stringify(daten, null, 4);

// Mit Tab-Zeichen

const formatiertTab = JSON.stringify(daten, null, ' ');

Ausgabe:
{

"name": "Max Mustermann",

"alter": 30,

"adresse": {

"stadt": "Berlin",

"plz": "10115"

}

}

Datei formatieren

const fs = require('fs');

// JSON-Datei lesen

const unformatiert = fs.readFileSync('daten.json', 'utf8');

const daten = JSON.parse(unformatiert);

// Formatiert zurückschreiben

fs.writeFileSync('daten.json', JSON.stringify(daten, null, 2));

console.log('Datei erfolgreich formatiert!');

Mit replacer-Funktion

const daten = {

name: "Max",

passwort: "geheim123",

alter: 30,

apiKey: "sk_test_123"

};

// Sensible Daten ausfiltern

const formatiert = JSON.stringify(daten, (key, value) => {

if (key === 'passwort' || key === 'apiKey') {

return '';

}

return value;

}, 2);

console.log(formatiert);

Ausgabe:

{

"name": "Max",

"passwort": "",

"alter": 30,

"apiKey": ""

}

Python

Grundlegende Formatierung

import json

daten = {

"name": "Max Mustermann",

"alter": 30,

"adresse": {

"stadt": "Berlin",

"plz": "10115"

}

}

# Mit 2 Leerzeichen

formatiert = json.dumps(daten, indent=2, ensure_ascii=False)

print(formatiert)

# Mit 4 Leerzeichen

formatiert4 = json.dumps(daten, indent=4, ensure_ascii=False)

# Sortierte Schlüssel

sortiert = json.dumps(daten, indent=2, sort_keys=True, ensure_ascii=False)

Datei formatieren

import json

# JSON-Datei lesen und formatieren

with open('daten.json', 'r', encoding='utf-8') as f:

daten = json.load(f)

# Formatiert zurückschreiben

with open('daten.json', 'w', encoding='utf-8') as f:

json.dump(daten, f, indent=2, ensure_ascii=False)

print('Datei erfolgreich formatiert!')

Kompakte vs. Formatierte Ausgabe

import json

daten = {"name": "Max", "alter": 30, "stadt": "Berlin"}

# Kompakt (für API-Antworten)

kompakt = json.dumps(daten, separators=(',', ':'))

print(kompakt) # {"name":"Max","alter":30,"stadt":"Berlin"}

# Formatiert (für Lesbarkeit)

formatiert = json.dumps(daten, indent=2)

print(formatiert)

Java

import com.google.gson.Gson;

import com.google.gson.GsonBuilder;

import com.google.gson.JsonParser;

public class JsonFormatter {

public static void main(String[] args) {

String unformatiert = "{"name":"Max","alter":30}";

// Gson mit Pretty Printing

Gson gson = new GsonBuilder()

.setPrettyPrinting()

.create();

// JSON parsen und formatieren

Object json = JsonParser.parseString(unformatiert);

String formatiert = gson.toJson(json);

System.out.println(formatiert);

}

}

PHP

<?php

$daten = [

"name" => "Max Mustermann",

"alter" => 30,

"adresse" => [

"stadt" => "Berlin",

"plz" => "10115"

]

];

// Mit Pretty Print (ab PHP 5.4)

$formatiert = json_encode($daten, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

echo $formatiert;

// Datei formatieren

$unformatiert = file_get_contents('daten.json');

$daten = json_decode($unformatiert);

file_put_contents('daten.json', json_encode($daten, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

?>

C#

using System;

using System.Text.Json;

class Program

{

static void Main()

{

var daten = new

{

Name = "Max Mustermann",

Alter = 30,

Adresse = new

{

Stadt = "Berlin",

PLZ = "10115"

}

};

// Mit Formatierung

var optionen = new JsonSerializerOptions

{

WriteIndented = true,

Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping

};

string formatiert = JsonSerializer.Serialize(daten, optionen);

Console.WriteLine(formatiert);

}

}

Online-Tools zum Formatieren

1. Big JSON (Empfohlen!)

Unser eigenes Tool mit erweiterten Funktionen:

  • Formatierung in Echtzeit
  • Syntax-Highlighting
  • Fehlerprüfung
  • Pfad-Explorer

2. JSONLint

https://jsonlint.com/

Features:

  • Validierung + Formatierung
  • Fehlererkennug
  • Einfache Benutzeroberfläche

3. JSON Formatter & Validator

https://jsonformatter.org/

Features:

  • Mehrere Ansichtsmodi
  • Baum-Ansicht
  • Download-Optionen

CLI-Tools

jq (Empfohlen)

# Installation (Linux)

sudo apt-get install jq

# Installation (macOS)

brew install jq

# Installation (Windows mit Chocolatey)

choco install jq

# JSON-Datei formatieren

jq '.' unformatiert.json > formatiert.json

# Mit sortieren Schlüsseln

jq --sort-keys '.' input.json > output.json

# Kompakt ausgeben

jq -c '.' input.json

# Nur bestimmte Felder

jq '.name, .alter' daten.json

json_pp (Perl)

# Normalerweise vorinstalliert auf Unix-Systemen

cat unformatiert.json | json_pp > formatiert.json

# Direkt in Datei

json_pp < input.json > output.json

Python (Einzeiler)

# Formatieren

python -m json.tool unformatiert.json formatiert.json

# Mit sortieren Schlüsseln

python -m json.tool --sort-keys input.json output.json

# In Pipeline

cat daten.json | python -m json.tool

Node.js (Einzeiler)

# Formatieren

node -e "console.log(JSON.stringify(JSON.parse(require('fs').readFileSync('input.json')), null, 2))" > output.json

# Als npm-Script in package.json

{

"scripts": {

"format:json": "node -e "console.log(JSON.stringify(JSON.parse(require('fs').readFileSync('data.json')), null, 2))" > data.json"

}

}

VS Code Integration

Eingebaute Formatierung

  • Öffnen Sie eine JSON-Datei
  • Drücken Sie \Shift + Alt + F\ (Windows/Linux) oder \Shift + Option + F\ (Mac)
  • Oder: Rechtsklick → "Dokument formatieren"
  • Einstellungen anpassen

    // settings.json
    

    {

    "editor.formatOnSave": true,

    "editor.tabSize": 2,

    "[json]": {

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

    "editor.formatOnSave": true,

    "editor.insertSpaces": true,

    "editor.tabSize": 2

    }

    }

    Prettier Extension

    // .prettierrc
    

    {

    "tabWidth": 2,

    "useTabs": false,

    "printWidth": 100,

    "trailingComma": "none"

    }

    Formatierungsoptionen

    Einrückung

    // 2 Leerzeichen (Standard)
    

    JSON.stringify(daten, null, 2)

    // 4 Leerzeichen

    JSON.stringify(daten, null, 4)

    // Tabs

    JSON.stringify(daten, null, ' ')

    Zeilen-Länge

    // Prettier mit maximal 80 Zeichen pro Zeile
    

    {

    "printWidth": 80

    }

    // Kompakter (längere Zeilen)

    {

    "printWidth": 120

    }

    Schlüssel sortieren

    import json
    
    

    daten = {"z": 1, "a": 2, "m": 3}

    # Sortierte Schlüssel

    sortiert = json.dumps(daten, sort_keys=True, indent=2)

    print(sortiert)

    Ausgabe:

    {
    

    "a": 2,

    "m": 3,

    "z": 1

    }

    Best Practices

    1. Konsistente Einrückung

    Verwenden Sie im gesamten Projekt die gleiche Einrückung:

    // ✅ Gut - 2 Leerzeichen überall
    

    {

    "projekt": {

    "name": "MeinProjekt",

    "version": "1.0.0"

    }

    }

    // ❌ Schlecht - Inkonsistent

    {

    "projekt": {

    "name": "MeinProjekt",

    "version": "1.0.0"

    }

    }

    2. Automatische Formatierung

    Richten Sie automatische Formatierung ein:

    // package.json
    

    {

    "scripts": {

    "format": "prettier --write '/.json'",

    "lint:json": "prettier --check '*/.json'"

    }

    }

    3. Git Hooks

    # .husky/pre-commit
    

    #!/bin/sh

    npm run format

    git add -A .

    4. EditorConfig

    # .editorconfig
    

    [.json]

    indent_style = space

    indent_size = 2

    end_of_line = lf

    charset = utf-8

    trim_trailing_whitespace = true

    insert_final_newline = true

    Häufige Probleme

    Problem 1: Ungültige JSON-Syntax

    try {
    

    const formatiert = JSON.stringify(JSON.parse(jsonString), null, 2);

    console.log(formatiert);

    } catch (error) {

    console.error('Ungültiges JSON:', error.message);

    // Zeigt genau, wo der Fehler ist

    }

    Problem 2: Encoding-Probleme

    import json
    
    

    # Sicherstellen, dass Umlaute richtig dargestellt werden

    formatiert = json.dumps(daten, indent=2, ensure_ascii=False)

    Problem 3: Große Dateien

    const fs = require('fs');
    

    const JSONStream = require('JSONStream');

    // Stream für große Dateien

    fs.createReadStream('groß.json')

    .pipe(JSONStream.parse(''))

    .pipe(JSONStream.stringify('{

    "daten": [

    ', ',

    ', '

    ]

    }'))

    .pipe(fs.createWriteStream('formatiert.json'));

    Batch-Formatierung

    Alle JSON-Dateien in einem Verzeichnis

    # Mit find und jq
    

    find . -name ".json" -exec jq '.' {} ; -exec sh -c 'jq "." "$1" > "$1.tmp" && mv "$1.tmp" "$1"' _ {} ;

    # Mit Python

    python -c "

    import json

    import glob

    for datei in glob.glob('/.json', recursive=True):

    with open(datei, 'r') as f:

    daten = json.load(f)

    with open(datei, 'w') as f:

    json.dump(daten, f, indent=2)

    "

    NPM-Script

    {
    

    "scripts": {

    "format:all": "prettier --write '*/.json' --ignore-path .gitignore"

    }

    }

    Zusammenfassung

    Schnellreferenz

    | Methode | Befehl |

    |---------|---------|

    | JavaScript | JSON.stringify(obj, null, 2) |

    | Python | json.dumps(obj, indent=2) |

    | CLI (jq) | jq '.' input.json |

    | CLI (Python) | python -m json.tool input.json |

    | VS Code | Shift + Alt + F |

    Wichtige Punkte

    ✅ Verwenden Sie 2 oder 4 Leerzeichen für Einrückung

    ✅ Aktivieren Sie automatische Formatierung beim Speichern

    ✅ Nutzen Sie Linter und Formatter-Tools

    ✅ Halten Sie die Formatierung im Team konsistent

    ✅ Validieren Sie JSON vor dem Formatieren

    Empfohlene Tools

  • VS Code mit Prettier Extension
  • jq für Kommandozeile
  • Big JSON für Online-Formatierung
  • Prettier für automatische Formatierung
  • Weiterführende Ressourcen

    Share:

    Verwandte Artikel

    Read in English