JSON-Formatierer und JSON-Validator Tools sind fur jeden Entwickler unverzichtbar, der mit APIs, Konfigurationsdateien und Datenaustausch arbeitet. Ob Sie JSON fur die Lesbarkeit formatieren, JSON online validieren oder fur das Debugging verschonern mussen, dieser umfassende Leitfaden deckt alles ab. Unser kostenloses Online-JSON-Formatierungs-Tool behandelt Formatierung, Validierung, Minifizierung und Syntaxfehlererkennung sofort in Ihrem Browser.
Testen Sie unser kostenloses JSON-Formatierungs- und Validierungstool.
Was ist JSON?
JSON (JavaScript Object Notation) ist ein leichtgewichtiges, textbasiertes Datenaustauschformat, das fur Menschen leicht zu lesen und zu schreiben ist und fur Maschinen leicht zu parsen und zu generieren. Es ist zum De-facto-Standard fur den Datenaustausch in Web-APIs, Konfigurationsdateien und NoSQL-Datenbanken geworden.
Ein JSON-Dokument besteht aus zwei Hauptstrukturen: Objekte (ungeordnete Sammlungen von Schlussel-Wert-Paaren in geschweiften Klammern {}) und Arrays (geordnete Listen von Werten in eckigen Klammern []). Werte konnen Strings, Zahlen, Booleans, null, Objekte oder Arrays sein.
JSON ist durch RFC 8259 und ECMA-404 definiert. Der Medientyp ist application/json und die Dateierweiterung ist .json. Im Gegensatz zu XML unterstutzt JSON keine Kommentare, Namensraume oder Attribute.
Warum Sie einen JSON-Formatierer brauchen
Lesbarkeit: Rohes JSON von APIs ist oft eine einzige lange Zeile. Ein JSON-Formatierer fugt Einruckungen und Zeilenumbruche hinzu.
Debugging: Bei API-Problemen hilft ein JSON-Validator, die genaue Position von Syntaxfehlern zu identifizieren.
Validierung: Validieren Sie JSON immer vor dem Deployment, um stille Fehler und Produktionsprobleme zu vermeiden.
Minifizierung: JSON minifizieren entfernt alle unnotigen Leerzeichen, reduziert Payload-Grossen und beschleunigt API-Antworten.
Haufige JSON-Syntaxfehler
Ein JSON-Syntaxfehler kann Ihre gesamte Anwendung zum Absturz bringen. Hier sind die haufigsten Fehler:
Nachgestellte Kommas: JSON erlaubt kein Komma nach dem letzten Element. {"a": 1, "b": 2,} ist ungultig.
// INVALID: trailing comma
{
"name": "John",
"age": 30,
}
// VALID: no trailing comma
{
"name": "John",
"age": 30
}Einfache Anfuhrungszeichen: JSON erfordert doppelte Anfuhrungszeichen. {'name': 'John'} ist ungultig.
// INVALID: single quotes
{'name': 'John', 'age': 30}
// VALID: double quotes
{"name": "John", "age": 30}Schlussel ohne Anfuhrungszeichen: Jeder Schlussel muss ein String in doppelten Anfuhrungszeichen sein.
Kommentare: Standard-JSON unterstutzt keine Kommentare. Verwenden Sie JSONC, YAML oder TOML.
// INVALID: comments not allowed in JSON
{
"name": "John", // this is a comment
"age": 30 /* block comment */
}
// VALID: no comments
{
"name": "John",
"age": 30
}undefined oder NaN: JSON unterstutzt nur null, nicht undefined, NaN oder Infinity.
// INVALID in JSON (JavaScript-specific values)
{
"value1": undefined,
"value2": NaN,
"value3": Infinity
}
// VALID: use null instead
{
"value1": null,
"value2": null,
"value3": null
}Fehlende Klammern: Jede offnende Klammer muss eine entsprechende schliessende haben.
Ungultige Escape-Sequenzen: JSON unterstutzt spezifische Escape-Sequenzen: \", \\, \n, \r, \t, \uXXXX.
Wie man JSON formatiert
Es gibt mehrere Methoden, JSON zu formatieren:
Online-JSON-Formatierer: Fugen Sie Ihre Daten in unser kostenloses Tool ein fur sofortige Formatierung und Validierung.
Kommandozeile mit jq: jq ist der leistungsstarkste JSON-Prozessor fur die Kommandozeile.
Python-Modul: python -m json.tool datei.json formatiert direkt vom Terminal.
IDE-Erweiterungen: VS Code hat eingebaute JSON-Formatierung (Shift+Alt+F). JetBrains bietet Ctrl+Alt+L.
Browser-DevTools: DevTools formatieren automatisch JSON-Antworten im Netzwerk-Tab.
JSON-Validierungsregeln
Um JSON korrekt zu validieren, hier die Regeln gemaess RFC 8259:
Datentypen: JSON unterstutzt sechs Typen: string, number, boolean, null, object und array.
// All six JSON data types demonstrated:
{
"string": "Hello World",
"number": 42.5,
"boolean": true,
"nullValue": null,
"object": {
"nested": "value"
},
"array": [1, "two", false, null, {"key": "val"}, [1,2,3]]
}Strings: Mussen in doppelten Anfuhrungszeichen stehen mit spezifischen Escape-Sequenzen.
Zahlen: Ganzzahlen oder Gleitkomma, wissenschaftliche Notation erlaubt, keine fuhrenden Nullen.
// Valid JSON numbers:
42 // integer
-17 // negative integer
3.14 // floating point
2.5e10 // scientific notation
-1.23e-4 // negative scientific notation
// INVALID JSON numbers:
01 // leading zero not allowed
.5 // must have digit before decimal
+1 // leading plus not allowed
0xFF // hex not allowed
0o77 // octal not allowed
NaN // not a valid JSON value
Infinity // not a valid JSON valueObjekte: Schlussel mussen einzigartige Strings sein. Leere Objekte {} sind gultig.
Arrays: Gemischte Typen erlaubt. Leere Arrays [] gultig. Beliebige Verschachtelung.
Kodierung: UTF-8 ist Standard und am weitesten verbreitet.
Top-Level-Wert: RFC 8259 erlaubt jeden JSON-Wert auf der obersten Ebene.
Codebeispiele: JSON formatieren und validieren
JavaScript: JSON formatieren und validieren
JavaScript bietet JSON.parse() und JSON.stringify() fur Validierung und Formatierung:
// ===== JSON.parse(): Validate JSON =====
// Valid JSON string
const jsonString = '{"name": "Alice", "age": 30, "active": true}';
const data = JSON.parse(jsonString);
console.log(data.name); // "Alice"
// Validate JSON safely with try/catch
function isValidJSON(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
console.error('JSON syntax error:', e.message);
return false;
}
}
isValidJSON('{"valid": true}'); // true
isValidJSON('{invalid: true}'); // false â "Unexpected token i"
isValidJSON('{"trailing": 1,}'); // false â "Unexpected token }"
// ===== JSON.stringify(): Format / Pretty Print JSON =====
const obj = {
name: "Alice",
age: 30,
address: {
city: "New York",
zip: "10001"
},
hobbies: ["reading", "coding", "hiking"]
};
// Pretty print with 2-space indentation
const formatted = JSON.stringify(obj, null, 2);
console.log(formatted);
/*
{
"name": "Alice",
"age": 30,
"address": {
"city": "New York",
"zip": "10001"
},
"hobbies": [
"reading",
"coding",
"hiking"
]
}
*/
// Pretty print with 4-space indentation
console.log(JSON.stringify(obj, null, 4));
// Pretty print with tab indentation
console.log(JSON.stringify(obj, null, "\t"));
// Minify JSON (no whitespace)
const minified = JSON.stringify(obj);
// {"name":"Alice","age":30,"address":{"city":"New York","zip":"10001"},...}
// Custom replacer: filter specific keys
const filtered = JSON.stringify(obj, ["name", "age"], 2);
/*
{
"name": "Alice",
"age": 30
}
*/
// Reviver function: transform values during parsing
const parsed = JSON.parse('{"date": "2025-01-15T00:00:00Z"}', (key, value) => {
if (key === 'date') return new Date(value);
return value;
});
console.log(parsed.date instanceof Date); // truePython: JSON formatieren und validieren
Pythons json-Modul bietet json.dumps() mit indent-Parameter:
import json
# ===== json.loads(): Validate JSON =====
json_string = '{"name": "Alice", "age": 30, "active": true}'
data = json.loads(json_string)
print(data["name"]) # "Alice"
# Validate JSON safely
def is_valid_json(s):
try:
json.loads(s)
return True
except json.JSONDecodeError as e:
print(f"JSON syntax error at line {e.lineno}, col {e.colno}: {e.msg}")
return False
is_valid_json('{"valid": true}') # True
is_valid_json('{invalid: true}') # False
is_valid_json('{"trailing": 1,}') # False
# ===== json.dumps(): Format / Pretty Print JSON =====
data = {
"name": "Alice",
"age": 30,
"address": {
"city": "New York",
"zip": "10001"
},
"hobbies": ["reading", "coding", "hiking"]
}
# Pretty print with 2-space indentation
formatted = json.dumps(data, indent=2)
print(formatted)
# Pretty print with sorted keys
formatted_sorted = json.dumps(data, indent=2, sort_keys=True)
print(formatted_sorted)
# Minify JSON (compact output)
minified = json.dumps(data, separators=(",", ":"))
print(minified)
# {"name":"Alice","age":30,"address":{"city":"New York","zip":"10001"},...}
# Handle non-ASCII characters (useful for i18n)
data_intl = {"city": "Tokyo", "greeting": "Hello"}
print(json.dumps(data_intl, ensure_ascii=False, indent=2))
# Read and format a JSON file
with open("data.json", "r") as f:
data = json.load(f)
with open("data_formatted.json", "w") as f:
json.dump(data, f, indent=2)
# Command line: python -m json.tool
# $ echo '{"a":1,"b":2}' | python -m json.tool
# {
# "a": 1,
# "b": 2
# }Kommandozeile: jq, python und node
Die Kommandozeile bietet verschiedene Werkzeuge zum Formatieren und Validieren von JSON:
# ===== jq: The Swiss Army knife for JSON =====
# Pretty print JSON
echo '{"name":"Alice","age":30}' | jq .
# {
# "name": "Alice",
# "age": 30
# }
# Minify JSON (compact output)
echo '{
"name": "Alice",
"age": 30
}' | jq -c .
# {"name":"Alice","age":30}
# Extract specific fields
echo '{"name":"Alice","age":30,"city":"NYC"}' | jq '{name, city}'
# {"name": "Alice", "city": "NYC"}
# Format a JSON file
jq . input.json > formatted.json
# Validate JSON (exit code 0 = valid, non-zero = invalid)
echo '{"valid": true}' | jq . > /dev/null 2>&1 && echo "Valid" || echo "Invalid"
echo '{invalid}' | jq . > /dev/null 2>&1 && echo "Valid" || echo "Invalid"
# Sort keys
echo '{"b":2,"a":1,"c":3}' | jq -S .
# {"a": 1, "b": 2, "c": 3}
# ===== python -m json.tool =====
# Format JSON from stdin
echo '{"a":1,"b":2}' | python3 -m json.tool
# Format a JSON file
python3 -m json.tool input.json output.json
# Sort keys
echo '{"b":2,"a":1}' | python3 -m json.tool --sort-keys
# ===== Node.js one-liner =====
# Pretty print JSON
echo '{"a":1,"b":2}' | node -e "process.stdin.resume();let d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>console.log(JSON.stringify(JSON.parse(d),null,2)))"
# Simpler: use node -p
node -p "JSON.stringify({a:1,b:[2,3]}, null, 2)"curl + jq Pipeline
Ein haufiger Workflow: JSON von einer API abrufen und sofort mit curl pipe zu jq formatieren:
# Fetch and format JSON from a REST API
curl -s https://api.github.com/users/octocat | jq .
# Fetch, extract specific fields, and format
curl -s https://api.github.com/users/octocat | jq '{login, name, bio, public_repos}'
# Fetch and validate (check exit code)
curl -s https://api.example.com/data | jq . > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo "Response is valid JSON"
else
echo "Response is NOT valid JSON"
fi
# POST JSON and format the response
curl -s -X POST https://api.example.com/data \
-H "Content-Type: application/json" \
-d '{"name":"Alice","age":30}' | jq .
# Save formatted JSON to file
curl -s https://api.github.com/users/octocat | jq . > user.json
# Minify before sending (reduce payload size)
DATA=$(jq -c . large-payload.json)
curl -s -X POST https://api.example.com/data \
-H "Content-Type: application/json" \
-d "$DATA" | jq .JSON Best Practices
Befolgen Sie diese Best Practices fur sauberes und performantes JSON:
camelCase fur Schlussel: Die meisten JSON-APIs verwenden camelCase. Seien Sie konsistent.
// camelCase (recommended for most APIs)
{
"firstName": "Alice",
"lastName": "Smith",
"phoneNumber": "+1-555-0123",
"isActive": true
}
// snake_case (common in Python/Ruby ecosystems)
{
"first_name": "Alice",
"last_name": "Smith",
"phone_number": "+1-555-0123",
"is_active": true
}Flache Verschachtelung: Tief verschachteltes JSON (mehr als 3-4 Ebenen) ist schwer lesbar.
// BAD: deeply nested (hard to read and parse)
{
"company": {
"departments": {
"engineering": {
"teams": {
"frontend": {
"members": [{"name": "Alice"}]
}
}
}
}
}
}
// BETTER: flattened structure
{
"companyId": "acme",
"departmentId": "engineering",
"teamId": "frontend",
"members": [{"name": "Alice"}]
}Grosse Dateien: Fur JSON-Dateien uber einige MB verwenden Sie Streaming-Parser.
JSON Schema: Validieren Sie Payloads gegen JSON Schema mit ajv oder jsonschema.
// JSON Schema example for validating user objects
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"name": { "type": "string", "minLength": 1 },
"age": { "type": "integer", "minimum": 0 },
"email": { "type": "string", "format": "email" },
"roles": {
"type": "array",
"items": { "type": "string" },
"minItems": 1
}
},
"required": ["name", "email"]
}Keine Binardaten: JSON ist ein Textformat. Verwenden Sie Base64 oder URLs fur Binardaten.
Konsistente null-Behandlung: Entscheiden Sie, ob null-Werte weggelassen oder explizit eingeschlossen werden.
JSON vs Alternativen: YAML, TOML, XML
JSON ist nicht das einzige Serialisierungsformat. Hier ein schneller Vergleich:
| Feature | JSON | YAML | TOML | XML |
|---|---|---|---|---|
| Readability | Good | Excellent | Excellent | Moderate |
| Comments | No | Yes | Yes | Yes |
| Data types | 6 types | Rich (dates, etc.) | Rich (dates, etc.) | Text only |
| Nesting | Unlimited | Unlimited | Limited | Unlimited |
| Multi-line strings | No | Yes | Yes | Yes (CDATA) |
| Parser support | Universal | Wide | Growing | Universal |
| File size | Small | Smaller | Smallest | Large (verbose) |
| Best for | APIs, data | Config files | Simple config | Documents, SOAP |
Wahlen Sie JSON fur APIs, YAML fur editierbare Konfigurationsdateien, TOML fur einfache Konfigurationen, XML fur bestehende Standards (SOAP, RSS).
Haufig gestellte Fragen
Wie formatiere ich JSON online?
Fugen Sie Ihr rohes JSON in ein Formatierungstool wie unseres ein. Das Tool validiert automatisch die Syntax, fugt Einruckungen hinzu und hebt Fehler hervor. Sie konnen zwischen 2- und 4-Leerzeichen-Einruckung wahlen. Das Tool lauft vollstandig in Ihrem Browser.
Was sind haufige JSON-Syntaxfehler?
Die haufigsten sind: nachgestellte Kommas, einfache statt doppelter Anfuhrungszeichen, Schlussel ohne Anfuhrungszeichen, Kommentare, undefined/NaN-Werte, fehlende Klammern und ungultige Escape-Sequenzen.
Was ist der Unterschied zwischen JSON und YAML?
JSON verwendet Klammern und doppelte Anfuhrungszeichen, YAML verwendet Einruckung. YAML unterstutzt Kommentare und mehrzeilige Strings. JSON eignet sich besser fur Maschine-zu-Maschine-Austausch, YAML fur Konfigurationsdateien. JSON ist eine strikte Untermenge von YAML.
Die Beherrschung von JSON-Formatierung und -Validierung ist fur moderne Entwickler unverzichtbar. Nutzen Sie unser kostenloses Tool fur sofortige Formatierung und Validierung.
JSON sofort formatieren, validieren und minifizieren mit unserem kostenlosen Tool.