Einstieg
Grundstruktur
JSON unterstützt 6 Datentypen: string, number, boolean, null, array und object. Keys müssen Strings in doppelten Anführungszeichen sein. JSON ist sprachunabhängig und für Menschen wie Maschinen leicht lesbar.
{
"name": "Alice",
"age": 30,
"isStudent": false,
"height": 1.65,
"nullValue": null,
"hobbies": ["reading", "coding", "music"],
"address": {
"city": "NYC",
"zip": "10001"
}
}JSON-Syntaxregeln
JSON hat strenge Syntax: Keys und Strings nutzen nur doppelte Anführungszeichen, Kommas trennen Elemente, und nachgestellte Kommas sind verboten. Das gesamte Dokument muss ein einziger JSON-Wert sein. Standard-JSON hat keine Kommentare — bei Bedarf einen Präprozessor oder JSON5 nutzen.
{
"key": "value", // key MUST be a double-quoted string
"nested": { "a": 1 }, // objects use { } with comma-separated pairs
"list": [1, 2, 3] // arrays use [ ] with comma-separated values
}
// Rules:
// - Double quotes only for strings and keys (no single quotes)
// - Comma separates members; NO trailing comma
// - The whole document is ONE value (usually an object or array)
// - No comments allowed in standard JSONKommentare in JSON
Standard-JSON verbietet Kommentare. Übliche Auswege: ein '_comment'-Feld ergänzen (wird vom Code ignoriert), JSONC/JSON5 nutzen (von VS Code und vielen Tools unterstützt), oder Kommentare vor dem Parsen mit einer Bibliothek wie comment-json oder JSON.minify entfernen.
// Standard JSON does NOT allow comments.
// Workaround 1: include a descriptive field
{
"_comment": "This is a config file for the app",
"port": 8080
}
// Workaround 2: use JSON5 or JSONC (VS Code settings)
{
// line comment
"port": 8080 /* block comment */
}
// Workaround 3: strip comments before parsing
// (e.g., JSON.minify, comment-json npm package)Whitespace & Formatierung
Whitespace außerhalb von Strings ist bedeutungslos — kompakte und hübsche Formen parsen zum selben Wert. Kompaktes JSON spart Bandbreite; pretty-printed (2-Zeichen-Einrückung ist üblich) hilft Lesbarkeit und diffs. Die meisten Serializer bieten eine 'pretty'-Option.
// These are all equivalent:
{"a":1,"b":2} // compact (no whitespace)
{ "a": 1, "b": 2 } // readable
{
"a": 1,
"b": 2
} // pretty-printed
// Whitespace between tokens is insignificant.
// Use compact for transmission, pretty for humans.Dateiendung & MIME-Typ
Die Standard-Dateiendung ist .json und der MIME-Typ application/json. Varianten wie JSONC, JSON5, GeoJSON und NDJSON haben eigene Konventionen. Immer UTF-8-Encoding nutzen; das BOM ist unerwünscht.
// File extensions:
// .json standard JSON
// .jsonc JSON with comments (VS Code, TypeScript config)
// .json5 JSON5 (relaxed syntax)
// .geojson GeoJSON (geographic data)
// .ndjson Newline-Delimited JSON (JSON Lines)
// .har HTTP Archive (JSON-based)
// MIME type:
Content-Type: application/json
// Older/alternate MIME types (avoid):
// text/json (non-standard)
// application/x-json (non-standard)
// UTF-8 is the default and recommended encoding.JSON-Wertkategorien
JSON-Werte fallen in sechs Typen: string, number, boolean, null, array, object. Arrays und Objekte sind strukturiert (können weitere Werte halten); der Rest sind Primitiva. Ein gültiges JSON-Dokument ist ein Wert — üblicherweise ein Objekt oder Array, aber eine nackte Zahl oder ein String ist auch gültig.
// A JSON value is exactly one of these six types:
"hello" // string
42 // number
3.14 // number
true // boolean
false // boolean
null // null
[1, 2, 3] // array
{ "a": 1 } // object
// Structured types: array, object
// Primitive types: string, number, boolean, null
// A standalone JSON document is a single value of any type.Datentypen
String-Typ
JSON-Strings sind in doppelte Anführungszeichen gesetzter Unicode-Text. Häufige Escapes: \" (Quote), \\ (Backslash), \/ (Slash), \n, \t, \r, \b, \f und \uXXXX für beliebigen Unicode-Codepoint. Einfache Anführungszeichen sind als String-Delimiter nicht erlaubt.
{
"single": "double quotes only",
"empty": "",
"escaped": "He said \"hi\" and C:\\Users",
"unicode": "Cafu00e9 \u00e9 \u1F600",
"multiline": "line1\nline2\ttabbed"
}
// Strings MUST use double quotes.
// Single quotes are NOT valid in JSON.Number-Typ
JSON-Zahlen folgen einer Teilmenge von IEEE 754 double-precision: Integer, Dezimalen und wissenschaftlicher Notation (z. B. 6.022e23). Führende Nullen sind verboten (007 ist ungültig). NaN, Infinity und -Infinity sind NICHT gültig — bei Bedarf als null oder String kodieren.
{
"integer": 42,
"negative": -7,
"float": 3.14,
"zero": 0,
"scientific": 6.022e23,
"small": 1.5e-10
}
// Numbers are NOT quoted.
// No leading zeros (007 is invalid).
// No NaN, Infinity, or -Infinity (not valid JSON).Boolean-Typ
JSON-Booleans sind die Literal-Keywords true und false (kleingeschrieben, ohne Anführungszeichen). Quoted 'true'/'false' sind Strings. JSON kennt kein Konzept von 0/1 oder yes/no als Booleans — in der Anwendungslogik konvertieren.
{
"enabled": true,
"disabled": false,
"flag": true
}
// Booleans are the bare keywords true and false.
// They are NOT quoted ("true" is a string).
// 0/1, yes/no, on/off are NOT booleans in JSON.Null-Typ
JSON null ist das nackte Keyword null (ohne Anführungszeichen). Es signalisiert die beabsichtigte Abwesenheit eines Werts. null ist nicht dasselbe wie ein leerer String '', 0, false oder ein fehlender Key. Viele Sprachen mappen null auf None/nil/null.
{
"middleName": null,
"deletedAt": null,
"optional": null
}
// null is a bare keyword (unquoted).
// "null" (quoted) is a string, not null.
// null represents the intentional absence of value.Array-Typ
JSON-Arrays sind geordnete Listen in [ ], kommasepariert, null-indexiert. Sie können jeden JSON-Wert halten, inklusive gemischter Typen und verschachtelter Arrays/Objekte. Leere Arrays [] sind gültig. Die Reihenfolge bleibt erhalten und ist bedeutsam.
{
"numbers": [1, 2, 3],
"mixed": [1, "two", true, null],
"nested": [[1, 2], [3, 4]],
"objects": [
{ "id": 1 },
{ "id": 2 }
],
"empty": []
}
// Arrays are ordered, zero-indexed, and can hold mixed types.Object-Typ
JSON-Objekte sind ungeordnete Key/Value-Sammlungen in { }. Keys müssen eindeutige Strings in doppelten Anführungszeichen sein; Werte können jeden JSON-Typ haben. Auch wenn Objekte konzeptionell ungeordnet sind, erhalten die meisten Parser die Einfügereihenfolge; für Korrektheit nicht auf die Reihenfolge verlassen.
{
"user": {
"id": 1,
"name": "Alice",
"roles": ["admin", "user"],
"active": true
},
"empty": {}
}
// Objects are unordered collections of key/value pairs.
// Keys MUST be unique strings (double-quoted).
// Values can be any JSON type.Strings
String-Grundlagen
JSON-Strings sind in doppelte Anführungszeichen gesetzte Unicode-Zeichenfolgen. Der Forward-Slash lässt sich escapen (\/) — nicht nötig, aber nützlich beim Einbetten von JSON in <script>-Tags. Leere Strings sind gültig.
{
"name": "Alice",
"email": "[email protected]",
"url": "https://example.com/path?q=1",
"path": "C:\\Users\\alice",
"empty": ""
}
// Strings are double-quoted Unicode text.
// Forward slash may be escaped as \/ but does not have to be.Escape-Sequenzen
JSON unterstützt diese Escapes: \" (Quote), \\ (Backslash), \/ (Slash), \b (backspace), \f (form feed), \n (newline), \r (carriage return), \t (tab) und \uXXXX (Unicode-Codepoint). Jede andere Backslash-Sequenz ist ungültig.
{
"quote": "She said \"hello\"",
"backslash": "C:\\Users\\name",
"newline": "line1\nline2",
"tab": "col1\tcol2",
"carriage": "a\rb",
"backspace": "a\bb",
"formfeed": "a\fb",
"slash": "a\/b"
}
// Valid escapes: \" \\ \/ \b \f \n \r \t \uXXXXUnicode-Zeichen
\uXXXX für beliebigen Unicode-Codepoint nutzen. Zeichen über U+FFFF (viele Emojis) brauchen ein surrogate pair: zwei \u-Escapes. Moderne Parser akzeptieren auch das rohe UTF-8-Zeichen direkt im String — \uXXXX ist vor allem zur Sicherheit oder wenn man das Zeichen nicht tippen kann.
{
"eacute": "Caf\u00e9",
"euro": "Price: \u20ac10",
"emoji": "Smile \ud83d\ude00",
"chinese": "\u4f60\u597d",
"raw": "Cafu00e9 u00e9 \u00e9"
}
// \uXXXX encodes a code point in the Basic Multilingual Plane.
// Surrogate pairs (two \u escapes) encode characters above U+FFFF.
// Modern parsers also accept the raw UTF-8 character directly.Sonderzeichen in Strings
Innerhalb von JSON-Strings müssen das doppelte Anführungszeichen und der Backslash immer escapet werden (\" und \\). Andere Sonderzeichen (HTML, SQL, Regex) folgen eigenen Regeln, aber JSON verlangt nur \" und \\ (plus Steuerzeichen). Ein Liter-Backslash wird als \\ geschrieben.
{
"html": "<div class=\"x\">Hi</div>",
"sql": "SELECT * FROM t WHERE name='O''Brien'",
"regex": "^\\d{3}-\\d{4}$",
"json": "{ \"k\": \"v\" }",
"cmd": "echo \"hello\""
}
// Backslash is the universal escape character.
// To include a literal backslash, write \\.Mehrzeilige Strings (Workaround)
JSON-Strings dürfen keine Literal-Zeilenumbrüche enthalten — sie müssen als \n escapet werden. Für mehrzeiligen Inhalt entweder \n im String einbetten, ein Array von Zeilen-Strings nutzen, oder auf ein Format wie YAML oder JSON5 mit Mehrzeilen-Strings wechseln. Literal unescapte Umbrüche sind ein Syntaxfehler.
// JSON does NOT support real multi-line strings.
// The following is INVALID:
// { "text": "line1
// line2" }
// Workaround 1: escape the newline
{ "text": "line1\nline2" }
// Workaround 2: array of lines
{ "lines": ["line1", "line2"] }
// Workaround 3: JSON5 allows continued strings (still single logical line)Häufige String-Fallstricke
Häufige String-Fehler: einfache Anführungszeichen, nachgestellte Kommas, vergessenes Escaping innerer doppelter Anführungszeichen und das Einbetten von Literal-Steuerzeichen (Tab/Umbruch) statt \t/\n. Ein strikter Parser lehnt all das ab.
// WRONG: single quotes
// { 'name': 'Alice' }
// WRONG: trailing comma
// { "a": 1, }
// WRONG: unescaped quote
// { "msg": "He said "hi"" }
// WRONG: literal tab/newline in string
// { "x": "a<TAB>b" }
// RIGHT:
{ "name": "Alice", "msg": "He said \"hi\"" }Zahlen
Integer & Float
JSON hat einen einzigen Zahlentyp, der Integer und Gleitkommawerte umfasst. Es gibt keinen separaten Integer-Typ auf Syntax-Ebene — Sprach-Bindings mappen große Integer je nach Wert und Bibliothek auf int, long, float oder decimal.
{
"count": 100,
"negative": -42,
"temperature": -273.15,
"pi": 3.14159,
"zero": 0,
"negativeZero": -0
}
// Integers and floats use the same number type.
// JSON does not distinguish int from float at the syntax level.Wissenschaftliche Notation
JSON unterstützt wissenschaftliche Notation: eine Mantisse gefolgt von e oder E und einem optionalen vorzeichenbehafteten Exponenten (6.022e23 = 6.022 * 10^23). Sowohl e als auch E werden akzeptiert. Essenziell für sehr große oder sehr kleine Zahlen in wissenschaftlichen Daten.
{
"avogadro": 6.022e23,
"planck": 6.626e-34,
"speedOfLight": 2.998e8,
"small": 1.5E-10
}
// e or E is allowed (case-insensitive).
// 6.022e23 means 6.022 * 10^23.
// The exponent may be negative.Zahlen-Präzision
JSON-Zahlen werden typischerweise als IEEE-754-Doubles geparst, also verlieren Integer über 2^53-1 (9007199254740991) in JavaScript Präzision. Dezimalwerte wie 0.1 sind exakt nicht darstellbar. Für Geld oder Integer mit beliebiger Präzision als Strings kodieren und im Code einen Decimal/BigInteger-Typ nutzen.
{
"big": 9007199254740993,
"decimal": 0.1,
"sum": 0.1,
"money": 19.99
}
// JavaScript stores numbers as IEEE 754 doubles.
// Integers are safe up to 2^53 - 1 (9007199254740991).
// 0.1 + 0.2 === 0.30000000000000004 (float precision loss).
// For money or big integers, parse as string or use a Decimal type.Sonderwerte (nicht erlaubt)
Standard-JSON erlaubt kein NaN, Infinity oder -Infinity. Auswege: null für NaN, Infinity als String kodieren, oder einen endlichen Sentinel-Wert nutzen. Manche Serializer (Pythons json per Default, JSON5) geben sie als Extensions aus, aber die Ausgabe ist nicht standardkonform und kann von strikten Parsern abgelehnt werden.
// NaN, Infinity, and -Infinity are NOT valid JSON.
// INVALID:
// { "x": NaN }
// { "y": Infinity }
// { "z": -Infinity }
// Common workarounds:
{
"x": null, // represent NaN/null
"y": "Infinity", // encode as a string
"z": 1.7976931348623157e308 // use a finite max
}
// Many serializers (e.g., Python json) accept these as extensions
// but the output is not standard JSON.Zahlen-Formate
Gültige JSON-Zahlen: optional Minus, Ganzzahl-Teil (keine führenden Nullen außer bei 0), optionaler Dezimalteil, optionaler Exponent. Hex (0x), binär (0b), oktal, Unterstriche, führendes +, führende Nullen und ein Punkt ohne Ziffern auf beiden Seiten sind alle ungültig.
// VALID JSON numbers:
42
-7
0
3.14
-0.5
6.022e23
1.5E-10
100.00
// INVALID:
007 // leading zero
.5 // no leading digit
5. // no trailing digit after dot
+5 // leading plus sign
0x1F // hex
0b101 // binary
1_000 // underscoresGroße Zahlen & BigInt
Für Werte über 2^53-1 (z. B. Twitter-Snowflake-IDs, 64-Bit-Integer, große Guthaben) als Strings kodieren, um Präzisionsverlust zu vermeiden. Muss man in JSON.parse einen reviver nutzen, um Zahlen zu BigInt zu wandeln: BigInt kann ohne replacer nicht wieder von JSON.stringify serialisiert werden — Strings sind auf der Leitung sicherer.
{
"snowflake": "1234567890123456789",
"timestamp": 1696000000000,
"balance": "99999999999999999999"
}
// Numbers above 2^53-1 lose precision in JS.
// Use STRINGS for IDs, snowflakes, and big integers.
// In JavaScript, parse with a reviver:
// JSON.parse(str, (k, v) =>
// typeof v === "number" && v > Number.MAX_SAFE_INTEGER
// ? BigInt(v) : v); // careful: BigInt can't be in JSON.stringify
// Better: keep them as strings on the wire.Booleans & Null
Boolean-Werte
JSON-Booleans sind die nackten Keywords true und false. Quoted 'true'/'false' sind Strings. JSON kennt auf Syntax-Ebene kein truthy/falsy — 1, 0, yes, no, on, off sind alle Strings oder Zahlen, keine Booleans. In der Anwendungslogik konvertieren.
{
"enabled": true,
"disabled": false,
"isPublic": true,
"isActive": false
}
// Only two boolean values: true and false (lowercase, unquoted).
// "true" (quoted) is a STRING, not a boolean.
// 1/0, yes/no, on/off are NOT booleans.Bedeutung von null
JSON null signalisiert die beabsichtigte Abwesenheit eines Werts. Es unterscheidet sich von einem fehlenden Key (Key nicht im Objekt), einem leeren String '', 0, false oder einer leeren Sammlung. null nutzen, wenn ein Feld existiert, aber keinen Wert hat; den Key weglassen, wenn das Feld nicht zutrifft.
{
"middleName": null,
"deletedAt": null,
"parent": null,
"optional": null
}
// null means "no value" or "intentionally absent".
// Distinct from:
// - missing key (key not present at all)
// - empty string ""
// - 0 or false
// - empty array [] or object {}Null vs. leer vs. fehlend
Drei verschiedene Zustände: ein Key mit leerem Wert (""), ein Key explizit null, und ein fehlender Key. In JavaScript bedeutet undefined, der Key fehlt, während null bedeutet, er ist da, aber ohne Wert. APIs sollten dokumentieren, welche Konvention sie für optionale Felder nutzen.
{
"name": "Alice",
"nickname": "", // empty string (present, empty)
"middleName": null, // explicit null (present, no value)
// "maidenName" // missing (key not in object)
}
// In JavaScript:
// obj.nickname === "" // true
// obj.middleName === null // true
// obj.maidenName === undefined // true (key absent)
// "maidenName" in obj // false
// Choose deliberately: null vs "" vs missing.Booleans in Bedingungen
Beim Konsum von JSON-Booleans strikten Vergleich (=== true) der truthy-Prüfung vorziehen, wenn false von fehlend unterschieden werden muss. In API-Antworten Boolean-Felder immer einschließen, auch wenn false — Weglassen zwingt Clients, den Default zu raten.
{
"isAdmin": true,
"canEdit": false,
"active": true
}
// In application code (JavaScript):
// if (user.isAdmin) { ... } // truthy check
// const canEdit = user.canEdit === true; // strict boolean check
// Be careful: a missing 'canEdit' key is undefined (falsy),
// but explicit false is also falsy. Distinguish if needed.
// API design: always send the boolean, even when false.Häufige Fallstricke
Häufige Fallstricke: true/false/null in Anführungszeichen macht sie zu Strings; True/TRUE/None (Python) oder true/false mit falscher Schreibweise ist ungültig; JSON hat kein undefined (nur null). Die einzigen gültigen Formen sind die kleingeschriebenen unquoted Keywords true, false und null.
// Pitfall 1: quoting booleans/null
// { "x": "true" } -> x is a STRING, not a boolean
// { "y": "null" } -> y is a STRING, not null
// Pitfall 2: wrong case
// { "x": True } -> INVALID (Python-style, not JSON)
// { "x": TRUE } -> INVALID
// { "x": None } -> INVALID
// Pitfall 3: confusing null with undefined
// null exists in JSON; undefined does NOT.
// Correct:
{ "x": true, "y": null }Arrays
Array-Grundlagen
JSON-Arrays sind geordnete, null-indexierte Listen in [ ], mit kommaseparierten Werten. Leere Arrays und Ein-Element-Arrays sind gültig. Die Reihenfolge ist bedeutsam und bleibt von Parsern erhalten. Ein nachgestelltes Komma ist nicht erlaubt.
{
"numbers": [1, 2, 3, 4, 5],
"strings": ["a", "b", "c"],
"booleans": [true, false, true],
"empty": [],
"single": [42]
}
// Arrays are ordered, zero-indexed lists in [ ].
// Elements are separated by commas (no trailing comma).
// Empty arrays [] and single-element arrays are valid.Arrays mit gemischten Typen
JSON-Arrays dürfen legal gemischte Typen halten ([1, 'two', true, null]). Das ist gültig, deutet aber oft auf schwaches Schemadesign hin. Homogene Arrays (alle Strings, alle Objekte) sind leichter zu validieren, zu dokumentieren und zu konsumieren. Ein Schema nutzen, um Elementtypen zu erzwingen.
{
"mixed": [1, "two", true, null, 3.14],
"nested": [[1, 2], "x", { "a": 1 }]
}
// JSON arrays CAN hold values of different types.
// This is valid but often a sign of weak schema design.
// Prefer homogeneous arrays for clarity and validation.Verschachtelte Arrays
Arrays verschachteln sich beliebig tief — nützlich für Matrizen, Gitter und Baumstrukturen. JSON erzwingt keine gleiche Länge verschachtelter Arrays (ein 'zerrissenes' Array ist gültig). Wer eine rechteckige Matrix braucht, erzwingt das per Schema oder Anwendungscode.
{
"matrix": [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
],
"ragged": [[1, 2], [3, 4, 5], [6]]
}
// Arrays can nest arbitrarily deep.
// JSON does not enforce rectangular shape—use a schema if needed.Array von Objekten
Ein Array von Objekten ist das häufigste Muster für Datensatzlisten (Nutzer, Produkte, Posts). Jedes Element hat typischerweise dieselbe Form, aber JSON erzwingt das nicht — mit einem Schema (JSON Schema 'items') validieren, dass alle Elemente entsprechen.
{
"users": [
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" },
{ "id": 3, "name": "Carol" }
],
"empty": []
}
// A very common pattern: a list of records.
// Each element is an object with the same shape.Leere & Ein-Element-Arrays
Leere Arrays [] und Ein-Element-Arrays sind gültig. Im API-Design [] (vorhanden, leere Liste) von null (vorhanden, keine Liste) und einem fehlenden Key (Feld trifft nicht zu) unterscheiden. [] für 'keine Elemente' zurückzugeben ist meistens freundlicher als null.
{
"empty": [],
"single": [42],
"tags": [],
"items": ["one"]
}
// Both forms are valid.
// Distinguish [] from null and from a missing key:
// "tags": [] -> present, empty list
// "tags": null -> present, no list
// // (no tags) -> missing keyArray-Zugriff im Code
Nach dem Parsen werden JSON-Arrays zu nativen Arrays/Listen der Sprache (JS Array, Python list, Java List usw.). Standard-Indexzugriff, length und Iteration nutzen. Grenzen und Typsicherheit sind die eigene Verantwortung — JSON selbst erzwingt keine Elementtypen.
{
"list": ["a", "b", "c"]
}
// JavaScript:
// const arr = JSON.parse(json).list;
// arr[0] // "a"
// arr.length // 3
// arr.includes("b") // true
// arr.map(x => x.toUpperCase()) // ["A", "B", "C"]
// Python:
// data = json.loads(json_str)
// data["list"][0] # "a"
// len(data["list"]) # 3Objekte
Objekt-Grundlagen
JSON-Objekte sind ungeordnete Sammlungen von Key/Value-Paaren in { }. Keys müssen Strings in doppelten Anführungszeichen sein; Werte können jeden JSON-Typ haben. Paare sind kommasepariert, ohne nachgestelltes Komma. Objekte sind die häufigste top-level JSON-Struktur.
{
"id": 1,
"name": "Alice",
"email": "[email protected]",
"active": true
}
// Objects are unordered { } collections of key/value pairs.
// Keys MUST be double-quoted strings.
// Pairs are comma-separated (no trailing comma).Key-Benennungsregeln
JSON-Keys dürfen jeder String in doppelten Anführungszeichen sein — inklusive leer, mit Leerzeichen, Punkten oder Ziffern. Für API-Klarheit aber konsistentes camelCase, snake_case oder kebab-case bevorzugen. Leerzeichen, Punkte (kollidieren mit Pfad-Syntax) und leere Keys in öffentlichen APIs vermeiden.
{
"simple": "ok",
"with-dash": "ok",
"with_underscore": "ok",
"with.dot": "ok",
"with space": "ok (but avoid)",
"123numeric": "ok (but avoid)",
"": "empty key is valid"
}
// Keys are arbitrary strings (double-quoted).
// Convention: use camelCase, snake_case, or kebab-case consistently.
// Avoid empty keys and keys with spaces/dots in APIs.Verschachtelte Objekte
Objekte verschachteln sich beliebig tief — nützlich für hierarchische Daten. Tiefe Verschachtelung ist gültig, kann aber Lesbarkeit schaden und Kopplung erhöhen. Für öffentliche APIs lieber eine flachere Struktur oder Referenzen (IDs) statt tief verschachtelter Bäume.
{
"user": {
"name": "Alice",
"address": {
"street": "123 Main St",
"city": "NYC",
"geo": { "lat": 40.7, "lng": -74.0 }
}
}
}
// Objects can nest arbitrarily deep.
// Deep nesting is valid but can hurt readability—flatten when sensible.Objekt mit Arrays
Die Kombination aus Objekten (für benannte Felder) und Arrays (für geordnete Listen) modelliert nahezu alle realen Daten. Ein verbreitetes Muster ist ein Objekt, das Arrays verschachtelter Objekte umwickelt (ein Nutzer mit Bestellungen). Ein Schema nutzen, um die erwartete Form zu dokumentieren und zu validieren.
{
"user": {
"name": "Alice",
"roles": ["admin", "user"],
"orders": [
{ "id": 1, "total": 19.99 },
{ "id": 2, "total": 5.99 }
]
}
}
// Combining objects and arrays models most real-world data.Member-Reihenfolge
Die JSON-Spec behandelt Objekte als ungeordnet. In der Praxis erhalten die meisten modernen Parser (JavaScript V8, Python 3.7+, Java LinkedHashMap) die Einfügereihenfolge, aber man sollte sich für Korrektheit nicht darauf verlassen. Ist die Reihenfolge wichtig für Hashing oder Signierung, Keys explizit sortieren.
{
"z": 1,
"a": 2,
"m": 3
}
// JSON objects are SPECIFIED as unordered.
// In practice, most parsers (JS, Python 3.7+) preserve insertion order.
// DO NOT rely on order for correctness—sort keys if order matters.
// Sorting keys (e.g., for stable hashing):
// JSON.stringify(obj, Object.keys(obj).sort())Doppelte Keys
Die JSON-Spec verbietet doppelte Keys nicht, aber ihr Verhalten ist undefiniert — die meisten Parser behalten den letzten Wert, manche den ersten. Doppelte Keys sind eine häufige Quelle subtiler Bugs. JSON Schema kann uniqueKeys erzwingen; Linter und strikte Parser können sie ablehnen.
// Technically valid JSON, but behavior is UNDEFINED:
{
"name": "Alice",
"name": "Bob"
}
// Most parsers keep the LAST value ("Bob"),
// but some keep the first. Avoid duplicate keys!
// JSON Schema (draft 2019-09+) has 'uniqueKeys' to forbid them.
// JSON.parse in JS keeps the last value (object property override).Verschachtelte Strukturen
Tiefe Verschachtelung
JSON erlaubt beliebige Verschachtelungstiefe, aber sehr tiefe Strukturen schaden der Lesbarkeit und können Parser-Grenzen treffen (viele setzen eine Tiefengrenze, z. B. 1000, um DoS zu verhindern). Für tief hierarchische Daten flachere Strukturen mit IDs/Referenzen bevorzugen.
{
"a": {
"b": {
"c": {
"d": {
"e": { "value": 42 }
}
}
}
}
}
// Nesting depth is theoretically unlimited.
// Many parsers impose a limit (e.g., 1000) to prevent DoS.
// Deep nesting hurts readability—consider flattening or references.Realwelt-Beispiel
Realwelt-JSON mischt Objekte und Arrays, um Entitäten und ihre Beziehungen zu modellieren. Dieses Bestellbeispiel verschachtelt customer, items (ein Array von Objekten) und shipping. Ein Schema nutzen, um die Form zu dokumentieren; die Verschachtelung für Lesbarkeit mäßig halten.
{
"order": {
"id": "ord-123",
"customer": {
"id": "cus-1",
"name": "Alice",
"email": "[email protected]"
},
"items": [
{ "sku": "A1", "qty": 2, "price": 9.99 },
{ "sku": "B2", "qty": 1, "price": 19.99 }
],
"shipping": {
"address": { "city": "NYC", "zip": "10001" },
"method": "express"
},
"total": 39.97
}
}Baumstrukturen
Bäume werden rekursiv modelliert: jeder Knoten hat einen Wert und ein Array von Kind-Knoten. Das Muster taucht in Dateisystemen, Organigrammen und ASTs auf. Auf Zyklen achten — JSON hat keine Referenz-Syntax, also müssen zyklische Graphen IDs nutzen oder als flache Liste mit parent pointers serialisiert werden.
{
"name": "root",
"children": [
{
"name": "child-a",
"children": [
{ "name": "grandchild-1", "children": [] },
{ "name": "grandchild-2", "children": [] }
]
},
{ "name": "child-b", "children": [] }
]
}
// Recursive structures: a node contains an array of child nodes.Verschachtelte Werte zugreifen
Der Zugriff auf tief verschachtelte Werte riskiert TypeError/KeyError, wenn Zwischen-Keys fehlen. Optional chaining (JS ?. und ??) oder verkettete .get() (Python) mit Defaults nutzen. Bibliotheken wie lodash.get oder jq vereinfachen die tiefe Extraktion und liefern Defaults.
{
"user": { "address": { "city": "NYC" } }
}
// JavaScript (optional chaining):
// const city = data?.user?.address?.city ?? "unknown";
// Python:
// city = data.get("user", {}).get("address", {}).get("city", "unknown")
// Deep access without guards throws on missing keys.
// Use optional chaining or a helper like lodash.get.Verschachtelte Daten glätten
Verschachtelte Objekte zu glätten (z. B. 'user.name' statt { user: { name } }) vereinfacht den Zugriff für Umgebungsvariablen, Formularfelder und Suchindexierung. Der Preis: Strukturverlust und schwereres Round-Tripping. Eine Bibliothek (flat, lodash) zum flatten/unflatten nutzen.
// Nested form:
{ "user": { "name": "Alice", "city": "NYC" } }
// Flattened form (dot notation):
{ "user.name": "Alice", "user.city": "NYC" }
// Flattened form (separate keys):
{ "userName": "Alice", "userCity": "NYC" }
// Use cases: environment variables, form fields, search indexing.
// Trade-off: simpler access vs. loss of structure.JSON Schema
Schema-Grundlagen
JSON Schema ist ein JSON-Vokabular zum Beschreiben und Validieren von JSON-Dokumenten. Die Wurzel deklariert $schema (Draft-Version) und type. Properties listet Felder mit ihren Typen; required listet Pflicht-Keys. Validatoren wie Ajv (JS) oder jsonschema (Python) prüfen die Konformität.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.com/user.json",
"title": "User",
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "integer", "minimum": 0 }
},
"required": ["name"]
}Typ-Validierung
Das 'type'-Keyword validiert den JSON-Typ eines Werts: string, number, integer, boolean, null, array oder object. Es kann ein einzelner Typ oder ein Array sein (z. B. ['string', 'null'] für einen optionalen nullable String). 'integer' matcht Zahlen ohne Dezimalteil.
{
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "integer" },
"active": { "type": "boolean" },
"score": { "type": "number" },
"tags": { "type": "array", "items": { "type": "string" } },
"meta": { "type": "object" },
"middle": { "type": ["string", "null"] }
}
}
// 'type' can be a single type or an array of allowed types.String-Constraints
String-Constraints: minLength, maxLength, pattern (Regex), enum (erlaubte Werte) und format (semantischer Hinweis wie 'email', 'uri', 'date-time', 'ipv4'). 'format' ist per Default nur eine Annotation — Validatoren müssen es explizit durchsetzen. Für strikte Regex-Validierung pattern nutzen.
{
"type": "object",
"properties": {
"email": {
"type": "string",
"format": "email",
"maxLength": 254
},
"username": {
"type": "string",
"pattern": "^[a-zA-Z0-9_]{3,20}$",
"minLength": 3,
"maxLength": 20
},
"bio": { "type": "string", "maxLength": 500 }
}
}
// 'format' is a semantic hint (email, uri, date, ipv4).
// 'pattern' is a regular expression.Zahlen-Constraints
Zahlen-Constraints: minimum, maximum (inklusive), exclusiveMinimum, exclusiveMaximum und multipleOf. Für den Typ 'integer' dürfen Werte keinen Dezimalteil haben. Constraints kombinieren, um Bereiche zu modellieren (z. B. eine Bewertung von 1 bis 5).
{
"type": "object",
"properties": {
"age": { "type": "integer", "minimum": 0, "maximum": 150 },
"price": { "type": "number", "minimum": 0, "exclusiveMinimum": 0 },
"rating":{ "type": "integer", "minimum": 1, "maximum": 5 },
"count": { "type": "integer", "multipleOf": 5 }
}
}
// minimum/maximum are inclusive;
// exclusiveMinimum/exclusiveMaximum are exclusive.Objekt- & Array-Constraints
Array-Constraints: items (Element-Schema), minItems, maxItems, uniqueItems. Objekt-Constraints: required (Pflicht-Keys), properties (Feld-Schemas), additionalProperties (false verbietet zusätzliche Keys, oder ein Schema dafür), minProperties, maxProperties.
{
"type": "object",
"properties": {
"id": { "type": "integer" },
"tags": {
"type": "array",
"items": { "type": "string" },
"minItems": 1,
"maxItems": 10,
"uniqueItems": true
}
},
"required": ["id"],
"additionalProperties": false
}
// minItems/maxItems/uniqueItems constrain arrays.
// required lists mandatory keys; additionalProperties
// controls whether extra keys are allowed.Fortgeschrittene Validierung
Fortgeschrittenes JSON Schema: oneOf/anyOf/allOf kombinieren Subschemata; $ref referenziert wiederverwendbare Definitionen; if/then/else wendet bedingte Validierung an; const verlangt einen exakten Wert; enum listet erlaubte Werte. Damit lassen sich reichhaltige Constraints und wiederverwendbare Typen ausdrücken.
{
"oneOf": [
{ "type": "string" },
{ "type": "integer" }
],
"definitions": {
"address": {
"type": "object",
"properties": { "city": { "type": "string" } }
}
},
"properties": {
"home": { "$ref": "#/definitions/address" },
"work": { "$ref": "#/definitions/address" }
},
"if": { "properties": { "type": { "const": "vip" } } },
"then": { "required": ["discount"] }
}
// oneOf/anyOf/allOf combine schemas.
// $ref reuses definitions; if/then/else is conditional.JSONPath
JSONPath-Syntax
JSONPath ist eine Abfragesprache für JSON, inspiriert von XPath. '$' ist die Wurzel, '.' wählt ein Kind, '[index]' wählt ein Array-Element, '*' ist ein Wildcard und '..' ist recursive descent. Bibliotheken wie jsonpath-plus (JS) oder jsonpath-ng (Python) implementieren sie.
// JSONPath queries JSON like XPath queries XML.
// Sample data:
{
"store": {
"book": [
{ "category": "fiction", "price": 12.99 },
{ "category": "web", "price": 29.99 }
]
}
}
// Common JSONPath expressions:
$.store.book[0].category // "fiction"
$.store.book[*].price // [12.99, 29.99]
$..price // all prices anywhere
$.store..category // all categories under storeRoot & Kind
'$' referenziert die Wurzel. '.' wählt ein Kind per Name; '[]' ist die Klammer-Alternative, die Keys mit Punkten, Leerzeichen oder Quotes behandelt. '[index]' wählt ein Array-Element (0-basiert); manche Implementierungen unterstützen negative Indizes fürs Zählen vom Ende.
// '$' = root object/array
// '.' or '[]' = child
$.user.name // dot notation
$['user']['name'] // bracket notation (use for special chars)
$.users[0] // first element of users array
$.users[-1] // last element (some implementations)
// Use bracket notation when keys contain dots, spaces, or quotes:
$['user.name']
$['first name']Recursive Descent
'..' (recursive descent) matcht einen Key oder ein Element in beliebiger Tiefe. '$..price' gibt jeden 'price'-Wert zurück, egal wo er auftaucht. '$..*' gibt jeden Knoten. Unbezahlbar, um große oder tief verschachtelte JSON zu durchsuchen, wenn man den exakten Pfad nicht kennt.
{
"a": { "b": { "c": 1 }, "c": 2 }
}
// '..' searches at all depths:
$..c // [1, 2] (all 'c' keys anywhere)
$..a // all 'a' keys
$..* // every node (everything)
// Useful for finding a key without knowing the exact path:
$..price // every price, no matter how nestedFilter-Ausdrücke
Filter nutzen [?(expression)], wobei '@' auf das aktuelle Element verweist. Unterstützte Operatoren variieren je Implementierung, umfassen aber typischerweise ==, !=, <, <=, >, >=, && (und), || (oder) und manchmal =~ für Regex. Funktionen wie length() und contains() ergänzen Kraft.
// Filter with [?(expression)]:
$.store.book[?(@.price < 20)] // books under 20
$.store.book[?(@.category == 'web')] // web books
$.store.book[?(@.price < 30 && @.category == 'web')]
// '@' refers to the current item being filtered.
// Operators: == != < <= > >= && || =~ (regex in some impls)
// Functions: length(), contains(), matches()Wildcards
'*' ist ein Wildcard, der alle Kinder eines Objekts oder alle Elemente eines Arrays matcht. '$.users[*].name' gibt den 'name' jedes Nutzers zurück. '$..*' gibt jeden Knoten. Ergebnisse kommen als Array von Treffern zurück, selbst wenn es nur einen gibt.
{
"users": [
{ "name": "Alice", "age": 30 },
{ "name": "Bob", "age": 25 }
]
}
// '*' matches all elements/children:
$.users[*] // all user objects
$.users[*].name // ["Alice", "Bob"]
$.users[0].* // all values of first user: ["Alice", 30]
$..* // every node in the document
// Wildcards return arrays of matches.Häufige Funktionen & Beispiele
JSONPath-Funktionen variieren je Implementierung: length(), min(), max(), avg(), sum(), contains() und matches() sind häufig. Filter und recursive descent kombinieren für mächtige Queries. Für CLI-Arbeit ist jq der De-facto-Standard und nutzt eine leicht andere Syntax.
// length(): array length or string length
$.users.length() // number of users
$.store.book[?(@.title.length() > 10)]
// min(), max(), avg(), sum() (some implementations)
$.store.book..price.min()
// Realistic query: titles of cheap web books
$.store.book[?(@.price < 20 && @.category == 'web')].title
// Tools: jq (CLI), jsonpath-plus (JS), jsonpath-ng (Python),
// Jayway (Java), GoJSONQ (Go)JSON vs. XML & YAML
JSON vs. XML-Syntax
JSON ist leichter (keine schließenden Tags, native Typen für Zahlen/Booleans/null) und mappt direkt auf die Datenstrukturen der meisten Sprachen. XML ist schwerer, aber reichhaltiger: Attribute, Namespaces, gemischter Inhalt, Schemas (XSD) und Transformationen (XSLT). JSON dominiert Web-APIs; XML hält sich im Enterprise/SOAP.
// JSON:
{
"name": "Alice",
"age": 30,
"hobbies": ["reading", "coding"]
}
<!-- XML: -->
<person>
<name>Alice</name>
<age>30</age>
<hobbies>
<hobby>reading</hobby>
<hobby>coding</hobby>
</hobbies>
</person>
// JSON: lighter, no closing tags, types (number/boolean/null).
// XML: heavier, supports attributes, namespaces, mixed content.JSON vs. YAML-Syntax
YAML nutzt Einrückung statt Klammern/Anführungszeichen, unterstützt Kommentare, mehrzeilige Strings und anchors/aliases. JSON ist strenger (Anführungszeichen Pflicht, keine Kommentare), aber schneller und überall verfügbar. YAML ist eine JSON-Obermenge — jede gültige JSON-Datei ist auch gültiges YAML.
# YAML:
name: Alice
age: 30
hobbies:
- reading
- coding
// JSON (equivalent):
{
"name": "Alice",
"age": 30,
"hobbies": ["reading", "coding"]
}
// YAML: no quotes/braces, indentation-based, supports comments.
// JSON: stricter, faster to parse, ubiquitous in APIs.JSON zu YAML konvertieren
JSON zu YAML zu konvertieren ist unkompliziert, weil YAML eine JSON-Obermenge ist. Pythons yaml.dump und Nodes js-yaml übernehmen das. Das Ergebnis nutzt Einrückung und (meistens) keine Anführungszeichen. YAMLs Kommentare und mehrzeilige Strings runden von JSON nicht her (JSON hat keine).
// JSON input:
{ "name": "Alice", "roles": ["admin", "user"] }
// YAML output:
name: Alice
roles:
- admin
- user
// Python:
// import yaml, json
// yaml.dump(json.loads(json_str), sort_keys=False)
// Node.js:
// const yaml = require('js-yaml');
// yaml.dump(JSON.parse(jsonStr));YAML zu JSON konvertieren
YAML zu JSON konvertieren funktioniert für einfaches YAML, verliert aber YAML-spezifische Features: Kommentare, anchors/aliases, Multi-Dokument-Streams, Tags und komplexe Keys. yaml.safe_load nutzen, um willkürliche Codeausführung über eigene Tags zu vermeiden. Das Ergebnis ist Standard-JSON.
# YAML input:
server:
host: localhost
port: 8080
debug: true
// JSON output:
{
"server": {
"host": "localhost",
"port": 8080,
"debug": true
}
}
// Python:
// import yaml, json
// json.dumps(yaml.safe_load(yaml_str), indent=2)
// Watch for YAML-specific features: anchors, tags, multi-docs.Datenmodellierungs-Unterschiede
JSON modelliert Daten als Objekte und Arrays — keine Attribute oder Namespaces. XML ergänzt Attribute, Namespaces, gemischten Inhalt und reichhaltige Schemas. YAML ergänzt Kommentare, Anchors und Multi-Dokument-Support. TOML zielt auf Config-Dateien mit Tabellen. Nach Bedarf wählen: APIs (JSON), Dokumente (XML), Konfiguration (YAML/TOML).
// JSON: objects and arrays, no attributes.
// Attribute-style metadata needs a convention (e.g., @_prefix).
// XML: elements + attributes, namespaces, mixed content.
// <book id="b1" category="web"><title>...</title></book>
// YAML: maps, sequences, scalars, anchors, multi-doc.
// Supports comments and multi-line strings natively.
// TOML: tables + key/value, designed for config files.
// Best for configuration; not ideal for nested data.Wann welches Format
JSON für Web-APIs und NoSQL-Storage (universell, schnell). XML für Enterprise-Services, dokumentzentrierte Daten (SVG, XHTML) und reichhaltige Schemas. YAML für von Menschen geschriebene Konfiguration (CI/CD, docker-compose) dank Kommentaren und Lesbarkeit. TOML für kleine Config-Dateien. Das Format an den Anwendungsfall anpassen.
// Use JSON when:
// - building web/REST APIs (universal browser support)
// - storing structured data (NoSQL databases)
// - configuration with simple needs (package.json)
// Use XML when:
// - enterprise/SOAP web services
// - documents with mixed content (SVG, XHTML, DocBook)
// - you need schemas, namespaces, or XSLT transforms
// Use YAML when:
// - human-written config (CI/CD, docker-compose)
// - you need comments and multi-line strings
// Use TOML when:
// - small config files (Cargo, pyproject)Parsen in JavaScript
JSON.parse
JSON.parse wandelt einen JSON-String in einen JavaScript-Wert. Es akzeptiert jeden gültigen JSON-Wert (Objekt, Array, String, Zahl, Boolean, null). Ungültiges JSON wirft einen SyntaxError. JSON.parse bei untrustetem Input immer in try/catch wickeln.
// Parse a JSON string into a JavaScript value.
const json = '{"name":"Alice","age":30}';
const obj = JSON.parse(json);
console.log(obj.name); // "Alice"
console.log(obj.age); // 30
// JSON.parse accepts a string only.
// Passing a number/boolean/object throws or coerces.
// JSON.parse("42") === 42 (valid)
// JSON.parse("true") === true (valid)
// JSON.parse("null") === null (valid)
// JSON.parse(undefined) // throws SyntaxErrorJSON.stringify
JSON.stringify wandelt einen JavaScript-Wert in einen JSON-String. Funktionen, Symbols und undefined werden weggelassen (in Objekten) oder zu null (in Arrays). BigInt wirft TypeError — erst in einen String wandeln. Das dritte Argument (space) für pretty-printing nutzen.
// Serialize a JavaScript value to a JSON string.
const obj = { name: "Alice", age: 30 };
const json = JSON.stringify(obj);
// '{"name":"Alice","age":30}'
// Pretty-print with 2-space indent:
JSON.stringify(obj, null, 2);
// {
// "name": "Alice",
// "age": 30
// }
// Functions, Symbols, and undefined are omitted.
// BigInt throws; use a replacer or String() first.Reviver-Funktion
Der JSON.parse-reviver transformiert Werte während des Parsens. Er wird von unten nach oben für jedes Key/Value-Paar aufgerufen (inklusive der Wurzel, mit Key ''). Den transformierten Wert zurückgeben oder undefined, um die Eigenschaft wegzulassen. Nützlich für Datumsparsen, BigInt und eigene Typen.
// JSON.parse accepts a 'reviver' to transform values.
const json = '{"date":"2024-01-15","count":"42"}';
const obj = JSON.parse(json, (key, value) => {
if (key === "date") return new Date(value);
if (key === "count") return Number(value);
return value;
});
// obj.date is a Date object; obj.count is a number.
// Reviver is called bottom-up for every key, including the root.Replacer-Funktion
Der JSON.stringify-replacer filtert oder transformiert Werte während der Serialisierung. Als Funktion wird er für jeden Key aufgerufen — undefined zurückgeben, um eine Eigenschaft wegzulassen. Als Array wirkt er als Allowlist der einzuschließenden Keys. Nützlich, um Secrets zu schwärzen und Felder zu wählen.
// JSON.stringify accepts a 'replacer' to filter/transform.
const obj = { name: "Alice", password: "secret", age: 30 };
// Replacer as a function:
const safe = JSON.stringify(obj, (key, value) => {
if (key === "password") return undefined; // omit
return value;
});
// '{"name":"Alice","age":30}'
// Replacer as an array (allowlist of keys):
JSON.stringify(obj, ["name", "age"]);
// '{"name":"Alice","age":30}'Pretty Printing
JSON.stringify ein space-Argument für pretty-printing mitgeben: eine Zahl (Einrückungstiefe) oder ein String (z. B. '\t'). Für stabile Key-Reihenfolge (nützlich für Hashing oder Signierung) Keys vor dem Stringifizieren sortieren. Mit einem replacer kombinieren, um beim Pretty-Printing Felder zu filtern.
const obj = { name: "Alice", age: 30 };
// Compact (default):
JSON.stringify(obj);
// '{"name":"Alice","age":30}'
// 2-space indent:
JSON.stringify(obj, null, 2);
// Tab indent:
JSON.stringify(obj, null, "\t");
// Combine replacer and indent:
JSON.stringify(obj, ["name", "age"], 2);
// To insert a stable key order, sort keys first:
const sorted = Object.keys(obj).sort()
.reduce((acc, k) => (acc[k] = obj[k], acc), {});
JSON.stringify(sorted, null, 2);Fehlerbehandlung
JSON.parse wirft bei ungültigem Input einen SyntaxError — bei untrusteten Daten immer in try/catch wickeln. Häufige Ursachen: nachgestellte Kommas, einfache Anführungszeichen, Kommentare oder abgeschnittener Input. Bei sehr großem oder tief verschachteltem JSON einen Streaming-Parser oder eine Tiefengrenze erwägen, um DoS zu verhindern.
// Always wrap JSON.parse in try/catch for untrusted input.
function safeParse(str) {
try {
return { ok: true, value: JSON.parse(str) };
} catch (e) {
return { ok: false, error: e.message };
}
}
// Common errors:
// SyntaxError: Unexpected token
// SyntaxError: Unexpected end of JSON input
// (no undefined/NaN/Infinity accepted)
// For deeply nested untrusted JSON, limit depth to avoid DoS.
// Consider a streaming parser for very large files.Parsen in Python
json.loads
json.loads parst einen JSON-String in Python-Objekte. JSON-Objekte werden dicts, Arrays Listen, Strings str, Zahlen automatisch int oder float, true/false zu True/False und null zu None. 'loads' steht für 'load string'.
import json
json_str = '{"name": "Alice", "age": 30}'
data = json.loads(json_str)
print(data["name"]) # Alice
print(data["age"]) # 30
# loads = "load string"
# Returns Python objects: dict, list, str, int/float, bool, None
# JSON true/false/null -> Python True/False/None
# JSON numbers -> int or float (auto)json.dumps
json.dumps serialisiert ein Python-Objekt in einen JSON-String. indent für pretty-printing, ensure_ascii=False, um Unicode-Zeichen zu behalten (statt \uXXXX-Escapes), und sort_keys=True für stabile Ausgabe. Pythons True/False/None mappt auf JSON true/false/null.
import json
data = {"name": "Alice", "age": 30, "active": True}
# Compact:
json.dumps(data)
# '{"name": "Alice", "age": 30, "active": true}'
# Pretty-printed:
json.dumps(data, indent=2, ensure_ascii=False)
# {
# "name": "Alice",
# "age": 30,
# "active": true
# }
# ensure_ascii=False keeps Unicode characters readable.
# sort_keys=True produces stable output.Dateien parsen
json.load (file object) und json.dump (file object) für Dateien; json.loads und json.dumps für Strings. Dateien immer mit encoding='utf-8' öffnen, um Plattform-Defaults zu vermeiden. Bei großen Dateien ijson (Streaming) oder orjson (schneller) für bessere Performance erwägen.
import json
# Read from a file:
with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f)
# Write to a file:
with open("out.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
# load/dump work on file objects; loads/dumps work on strings.
# Always specify encoding="utf-8" for portability.Eigene Encoder
json.JSONEncoder ableiten und default() überschreiben, um Typen zu serialisieren, die JSON nicht nativ unterstützt (datetime, set, Decimal, eigene Klassen). Eine JSON-serialisierbare Repräsentation zurückgeben. Zum Dekodieren einen eigenen hook (object_hook) schreiben, der die Transformation umkehrt.
import json
from datetime import datetime, date
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (datetime, date)):
return obj.isoformat()
if isinstance(obj, set):
return sorted(obj)
return super().default(obj)
data = {"now": datetime.now(), "tags": {"a", "b"}}
json.dumps(data, cls=CustomEncoder)
# '{"now": "2024-...", "tags": ["a", "b"]}'
# The default() method is called for objects json can't serialize.Fehlerbehandlung
json.loads wirft bei ungültigem Input json.JSONDecodeError mit Zeilen-/Spalten-Info. Häufige Ursachen: nachgestellte Kommas, einfache Anführungszeichen, Kommentare, NaN/Infinity (per Default abgelehnt) und Steuerzeichen in Strings. Bei Bedarf parse_constant nutzen, um NaN/Infinity/-Infinity zu handhaben.
import json
def safe_loads(s):
try:
return {"ok": True, "value": json.loads(s)}
except json.JSONDecodeError as e:
return {"ok": False, "error": str(e), "line": e.lineno, "col": e.colno}
# json.JSONDecodeError gives line and column of the error.
# Common causes: trailing commas, single quotes, comments,
# NaN/Infinity (rejected by default), control chars in strings.
# To allow NaN/Infinity (non-standard):
json.loads('{"x": NaN}', parse_constant=lambda x: None) # or float(x)Decimal & DateTime behandeln
Per Default parst json alle Zahlen als float und verliert bei Dezimalen wie Geld Präzision. parse_float=Decimal übergeben, um Präzision zu behalten, und mit einem default-hook serialisieren, der Decimal zurückwandelt (zu str, um Präzision zu erhalten, oder float, wenn Verlust akzeptabel ist). Für exakte Geld-Darstellung str nutzen.
import json
from decimal import Decimal
from datetime import datetime
# Decimal: parse_float keeps precision (default would lose it)
data = json.loads('{"price": 19.99}', parse_float=Decimal)
print(data["price"]) # Decimal('19.99')
print(data["price"] + Decimal("0.01")) # 20.00 exact
# Serialize Decimal back:
def encode(obj):
if isinstance(obj, Decimal):
return float(obj) # or str(obj) to keep precision
raise TypeError
json.dumps({"price": Decimal("19.99")}, default=encode)
# parse_float=float is the default; use Decimal for money.Parsen in Java
Jackson-Grundlagen
Jackson ist die populärste Java-JSON-Bibliothek. ObjectMapper.readValue parst JSON in POJOs; writeValueAsString serialisiert sie. jackson-databind (plus jackson-core und jackson-annotations) als Dependencies ergänzen. Jackson ist schnell, ausgereift und integriert sich per Default mit Spring Boot.
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
// Parse JSON to a Java object:
String json = "{\"name\":\"Alice\",\"age\":30}";
User user = mapper.readValue(json, User.class);
// Serialize a Java object:
String out = mapper.writeValueAsString(user);
// Pretty-print:
String pretty = mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(user);
// Jackson is the de facto JSON library for Java.
// Add: com.fasterxml.jackson.core:jackson-databindGson-Grundlagen
Gson ist Googles JSON-Bibliothek, für die Grundnutzung einfacher als Jackson. Gson.fromJson parst; toJson serialisiert. GsonBuilder für Optionen (pretty printing, null-Serialisierung, eigene Adapter). com.google.code.gson:gson als Dependency ergänzen. Gson ist auf Android verbreitet.
import com.google.gson.Gson;
Gson gson = new Gson();
// Parse:
User user = gson.fromJson(json, User.class);
// Serialize:
String out = gson.toJson(user);
// Pretty-print:
Gson pretty = new GsonBuilder().setPrettyPrinting().create();
String s = pretty.toJson(user);
// Gson (by Google) is simpler than Jackson for basic use.
// Add: com.google.code.gson:gsonJsonNode-Baummodell
Jacksons JsonNode ist ein Baummodell zum Navigieren von JSON ohne POJO. get() (gibt null zurück, wenn fehlend) oder path() (liefert einen sicheren 'missing node' für Verkettung) nutzen. asText/asInt/asBoolean haben Overloads mit Default-Wert. Nützlich, wenn das Schema unbekannt oder variabel ist.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(json);
String name = root.get("name").asText(); // "Alice"
int age = root.get("age").asInt(); // 30
JsonNode hobbies = root.get("hobbies"); // array
for (JsonNode h : hobbies) {
System.out.println(h.asText());
}
// get() returns null for missing keys; path() returns a
// 'missing node' that you can chain safely.
String city = root.path("address").path("city").asText("unknown");Eigene Deserialisierung
Ein eigener JsonDeserializer behandelt nicht-standardkonforme JSON-Kodierungen (z. B. '$19.99' für Geld). Ein Feld mit @JsonDeserialize(using = ...) annotieren oder ein SimpleModule für einen Typ registrieren. JsonSerializer für eigene Serialisierung. So bleiben POJOs frei von Parsing-Logik.
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.core.*;
import java.io.IOException;
public class MoneyDeserializer extends JsonDeserializer<Double> {
@Override
public Double deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException {
String s = p.getText(); // e.g. "$19.99"
return Double.parseDouble(s.replaceAll("[^0-9.]", ""));
}
}
// Annotate the field:
// @JsonDeserialize(using = MoneyDeserializer.class)
// public double price;
// Or register a module for a type.Streaming-API
Jacksons Streaming-API (JsonParser/JsonGenerator) liest und schreibt JSON Token für Token mit konstantem Speicher — ideal für riesige Dateien. Man kontrolliert die Parsing-Schleife und kann Teilbäume mit skipChildren() überspringen. Mit dem Baum- oder POJO-Modell für die tatsächlich benötigten Teile paaren.
import com.fasterxml.jackson.core.*;
// Jackson streaming: low memory, fast, for huge files.
JsonFactory f = new JsonFactory();
try (JsonParser p = f.createParser(new File("huge.json"))) {
while (p.nextToken() != JsonToken.END_OBJECT) {
String field = p.getCurrentName();
if ("name".equals(field)) {
p.nextToken();
System.out.println(p.getText());
}
// skip complex values you don't need:
// p.skipChildren();
}
}
// Use streaming for files that won't fit in memory.Parsen in PHP
json_encode
json_encode serialisiert einen PHP-Wert nach JSON. PHP-Arrays werden JSON-Objekte (assoziativ) oder Arrays (sequenziell). Häufige Flags: JSON_PRETTY_PRINT, JSON_UNESCAPED_UNICODE (lesbares Unicode behalten), JSON_UNESCAPED_SLASHES (/ nicht escapen). Flags mit dem |-Operator kombinieren.
<?php
$data = ["name" => "Alice", "age" => 30, "active" => true];
// Compact (default):
$json = json_encode($data);
// {"name":"Alice","age":30,"active":true}
// Pretty-print:
$pretty = json_encode($data, JSON_PRETTY_PRINT);
// Keep Unicode readable (don't escape to \uXXXX):
$unicode = json_encode($data, JSON_UNESCAPED_UNICODE);
// Combine flags with |:
json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE
| JSON_UNESCAPED_SLASHES);json_decode
json_decode parst JSON nach PHP. Das zweite Argument steuert das Ergebnis: true liefert assoziative Arrays, false (Default) stdClass-Objekte. Je nach Zugriffsstil wählen ($arr['key'] vs. $obj->key). PHP-Arrays mit nicht-sequenziellen Keys werden zu JSON-Objekten.
<?php
$json = '{"name":"Alice","age":30,"hobbies":["reading"]}';
// Default: returns associative array OR object (stdClass)
$data = json_decode($json);
echo $data->name; // Alice
// Force associative array:
$arr = json_decode($json, true);
echo $arr["name"]; // Alice
// The second argument (assoc) controls array vs object.
// PHP objects become stdClass instances by default.Fehlerbehandlung
PHPs json_decode wirft per Default nicht — nach dem Parsen json_last_error() und json_last_error_msg() prüfen. JSON_THROW_ON_ERROR übergeben (PHP 7.3+), damit es stattdessen eine JsonException wirft, was sauberer ist. Häufige Fehler: nachgestellte Kommas, einfache Anführungszeichen und ungültiges UTF-8.
<?php
$json = '{invalid json}';
$data = json_decode($json);
if (json_last_error() !== JSON_ERROR_NONE) {
echo "Parse error: " . json_last_error_msg();
// e.g., "Syntax error"
}
// PHP does not throw on JSON errors; check json_last_error().
// Common errors: trailing comma, single quotes, invalid UTF-8.
// To throw exceptions instead:
try {
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo $e->getMessage();
}Pretty Print & Flags
Häufige json_encode-Flags: JSON_PRETTY_PRINT (Einrückung), JSON_UNESCAPED_UNICODE (lesbares Nicht-ASCII behalten), JSON_UNESCAPED_SLASHES (/ nicht escapen), JSON_NUMERIC_CHECK (numerische Strings in Zahlen wandeln), JSON_THROW_ON_ERROR (bei Fehlschlag werfen). Mit | kombinieren.
<?php
$data = ["path" => "C:\\Users", "url" => "https://x.com/"];
// Default escapes / and non-ASCII:
json_encode($data);
// {"path":"C:\\Users","url":"https:\/\/x.com\/"}
// Cleaner output:
json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
| JSON_PRETTY_PRINT);
// {
// "path": "C:\\Users",
// "url": "https://x.com/"
// }
// JSON_NUMERIC_CHECK converts numeric strings to numbers:
json_encode(["id" => "42"], JSON_NUMERIC_CHECK); // {"id":42}Eigene Serialisierung
JsonSerializable implementieren und jsonSerialize() definieren, um zu steuern, wie ein Objekt kodiert wird. Der sauberste Weg, Felder zu schwärzen (z. B. password weglassen), Keys umzubenennen oder abgeleitete Werte während der Serialisierung zu berechnen. Die Methode gibt eine beliebige JSON-serialisierbare Struktur zurück.
<?php
class User implements JsonSerializable {
public $name;
public $password;
public function __construct($name, $password) {
$this->name = $name;
$this->password = $password;
}
public function jsonSerialize(): mixed {
return [
"name" => $this->name,
// omit password for security
];
}
}
echo json_encode(new User("Alice", "secret"));
// {"name":"Alice"}
// JsonSerializable lets the class control its JSON form.JSON:API-Spezifikation
Dokumentstruktur
JSON:API ist eine Spezifikation für konsistente JSON-APIs. Ein Dokument hat ein top-level 'jsonapi'-Versionsobjekt, eine primäre 'data'-Ressource, optionale 'included'-verwandte Ressourcen, 'meta' für nicht-standard Infos, 'links' für Pagination und 'errors' für Fehler. Der Medientyp ist application/vnd.api+json.
{
"jsonapi": { "version": "1.1" },
"data": {
"type": "articles",
"id": "1",
"attributes": {
"title": "JSON:API Basics"
},
"relationships": {
"author": { "data": { "type": "people", "id": "9" } }
}
},
"included": [
{ "type": "people", "id": "9", "attributes": { "name": "Jane" } }
]
}
// JSON:API is a convention for building JSON APIs.
// Top-level keys: jsonapi, data, errors, meta, links, included.Ressourcen-Objekte
Ein JSON:API-Ressourcen-Objekt hat ein 'type' (die Ressourcenart) und 'id' (einen String-Identifikator), dazu 'attributes' (die Daten) und optional 'relationships' (Links zu anderen Ressourcen) und 'links' (URLs wie self). IDs müssen Strings sein. type und id dürfen nicht in attributes auftauchen.
{
"data": {
"type": "articles",
"id": "1",
"attributes": {
"title": "Hello",
"published": true,
"views": 42
},
"links": {
"self": "/articles/1"
}
}
}
// Every resource has a 'type' (string) and 'id' (string).
// 'attributes' holds data; 'relationships' holds links to others.
// 'id' and 'type' MUST NOT appear inside attributes.Beziehungen
Beziehungen verknüpfen eine Ressource mit anderen über Ressourcen-Identifikator-Objekte ({type, id}). to-one-Beziehungen nutzen einen einzelnen Identifikator; to-many ein Array. Das 'links'-Objekt liefert 'self' (die Beziehungs-URL) und 'related' (die URL der verwandten Ressource) zur Navigation.
{
"data": {
"type": "articles",
"id": "1",
"relationships": {
"author": {
"data": { "type": "people", "id": "9" },
"links": {
"self": "/articles/1/relationships/author",
"related": "/articles/1/author"
}
},
"tags": {
"data": [
{ "type": "tags", "id": "1" },
{ "type": "tags", "id": "2" }
]
}
}
}
}
// to-one: data is a single resource identifier.
// to-many: data is an array of resource identifiers.Meta & Links
'meta' trägt nicht-standard Informationen wie Gesamtzählungen, Rate-Limits oder Warnungen. 'links' liefert Hypermedia-Navigation: self, first, prev, next, last für Pagination, dazu related-URLs. null für einen fehlenden Link nutzen (z. B. prev auf der ersten Seite).
{
"meta": {
"totalPages": 5,
"currentPage": 1,
"rateLimit": 100
},
"links": {
"self": "/articles?page=1",
"first": "/articles?page=1",
"prev": null,
"next": "/articles?page=2",
"last": "/articles?page=5"
},
"data": [ /* ... */ ]
}
// meta: non-standard metadata (counts, rate limits, etc.).
// links: pagination and resource URLs.Fehler
JSON:API-Fehlerdokumente haben ein top-level 'errors'-Array (und kein 'data'). Jedes Fehlerobjekt hat optionale Felder: id, status (HTTP-Code als String), code (App-spezifisch), title (kurze Zusammenfassung), detail (menschliche Erklärung), source (Verweis auf das schlechte Feld via JSON Pointer) und meta.
{
"errors": [
{
"id": "err-123",
"status": "404",
"code": "NOT_FOUND",
"title": "Resource Not Found",
"detail": "Article 99 does not exist.",
"source": { "pointer": "/data/attributes/id" },
"meta": { "requestId": "abc-9" }
}
]
}
// Errors is an array of error objects.
// status: HTTP status string; code: app-specific code.
// source.pointer: JSON Pointer to the offending field.JSON5
JSON5-Features
JSON5 ist eine Obermenge von JSON, entworfen für von Menschen geschriebene Konfiguration. Sie ergänzt Kommentare, unquoted/einfach-quoted Strings, nachgestellte Kommas, hex/Infinity/NaN-Zahlen und entspannte Zahlenformate. JSON5 ist kein Standard-JSON — einen JSON5-Parser nutzen (json5 npm package) und für den Austausch zu JSON konvertieren.
// JSON5 is a superset of JSON with friendlier syntax.
{
// line comments
/* block comments */
unquotedKey: "ok", // unquoted keys
"with space": "ok", // quoted keys still allowed
singleQuote: 'single', // single-quoted strings
trailing: [1, 2, 3,], // trailing commas
hex: 0x1F, // hexadecimal numbers
inf: Infinity, // Infinity, -Infinity, NaN
leadingDot: .5, // leading decimal point
trailingDot: 5., // trailing decimal point
plus: +5, // leading plus
}
// JSON5 is NOT standard JSON—use a JSON5 parser.Kommentare
JSON5 unterstützt // Zeilenkommentare wie /* */-Blockkommentare, die Standard-JSON verbietet. Das macht JSON5 ideal für von Menschen geschriebene Config-Dateien. VS Codes settings.json und TypeScripts tsconfig.json nutzen JSONC (JSON mit Kommentaren), eine ähnliche, aber leicht andere Teilmenge.
{
// Single-line comment (like JS)
"name": "Alice",
/* Block comment
spanning multiple lines */
"age": 30,
"active": true // end-of-line comment
}
// Standard JSON rejects comments.
// JSON5 supports // and /* */ comments everywhere.
// VS Code's settings.json and tsconfig.json use JSONC (a subset).Nachgestellte Kommas
JSON5 erlaubt nachgestellte Kommas nach dem letzten Element von Objekten und Arrays. Standard-JSON lehnt sie ab. Nachgestellte Kommas verringern diff-Rauschen beim Ergänzen oder Umordnen von Feldern (jede Zeile kann mit Komma enden). Viele moderne Sprachen und Config-Formate erlauben das inzwischen.
{
"a": 1,
"b": 2,
"c": 3, // <-- trailing comma OK in JSON5
}
// Arrays too:
[1, 2, 3,]
// Standard JSON rejects trailing commas.
// JSON5 allows them, reducing diff noise when adding fields.Unquoted & einfach-quoted Strings
JSON5 erlaubt unquoted Identifier-Keys (passend zu [A-Za-z_$][A-Za-z0-9_$]*) sowie sowohl einfach- als auch doppel-quoted Strings. Innerhalb eines einfach-quoted Strings ' als \' escapen; innerhalb eines doppel-quoted " als \". Das spiegelt die JavaScript-Objekt-Literal-Syntax zur besseren Lesbarkeit wider.
{
unquoted: "value", // unquoted identifier key
"quoted key": "value", // quoted key (for special chars)
single: 'single-quoted', // single-quoted string value
mixed: 'it\'s ok', // escape single quote inside
double: "she said \"hi\"", // escape double quote inside
}
// Unquoted keys must be valid identifiers ([A-Za-z_$][A-Za-z0-9_$]*).
// Single and double quotes are both allowed for strings.Zahlen & Strings (erweitert)
JSON5 erweitert Zahlen: hexadezimal (0xFF), führende/nachgestellte Dezimalpunkte (.5, 5.), führendes Plus (+5) und die Keywords Infinity, -Infinity und NaN. All das lehnt Standard-JSON ab. JSON5-Strings nutzen weiterhin Escape-Sequenzen (\n) für Umbrüche — nackte mehrzeilige Strings gibt es nicht.
{
hex: 0xFF, // hexadecimal
leadingDot: .5, // .5 instead of 0.5
trailingDot: 5., // 5. instead of 5.0
leadingPlus: +5, // +5 (standard JSON rejects +)
infinity: Infinity, // Infinity (not in standard JSON)
negativeInfinity: -Infinity,
nan: NaN,
multiline: 'line1\nline2' // escape sequences like JSON
}
// JSON5 does NOT support real multi-line strings or bareword NaN.JSON Lines (JSONL)
JSONL-Format
JSON Lines (JSONL oder NDJSON) ist ein Format, bei dem jede Zeile ein separater, vollständiger JSON-Wert ist. Es gibt kein umschließendes Array. Ideal für Streaming, Logs und große Datensätze: zeilenweise verarbeiten, ohne die ganze Datei zu laden. Endungen: .jsonl, .ndjson.
// A JSON Lines file (.jsonl / .ndjson) is one JSON value per line:
{"name": "Alice", "age": 30}
{"name": "Bob", "age": 25}
{"name": "Carol", "age": 35}
// Rules:
// - Each line is a COMPLETE, valid JSON value.
// - Lines are separated by newlines (\n).
// - No enclosing [ ] array.
// - Each line is parsed independently.JSONL lesen
JSONL lesen, indem man Zeilen iteriert und jede mit JSON.parse/loads parst. Das streamt die Datei mit konstantem Speicher — ideal für riesige Datensätze. Leerzeilen überspringen. In Node.js readline über einen file stream; in Python das file object direkt iterieren. Keine Notwendigkeit, die ganze Datei zu laden.
// JavaScript (Node.js) — line by line:
const fs = require("fs");
const readline = require("readline");
const rl = readline.createInterface({
input: fs.createReadStream("data.jsonl"),
crlfDelay: Infinity,
});
for await (const line of rl) {
if (!line.trim()) continue;
const obj = JSON.parse(line);
console.log(obj.name);
}
// Python:
// import json
// with open("data.jsonl") as f:
// for line in f:
// obj = json.loads(line)JSONL schreiben
JSONL schreiben, indem man jeden Datensatz mit JSON.stringify/dumps serialisiert (kompakt, ohne Einrückung) und einen Zeilenumbruch anhängt. Einen writable stream (Node) oder die Datei im write-Modus öffnen (Python) für Effizienz. Kompakte Form hält Zeilen kurz und parsebar; ein Datensatz pro Zeile ist die Regel.
// JavaScript (Node.js):
const fs = require("fs");
const out = fs.createWriteStream("out.jsonl");
for (const obj of records) {
out.write(JSON.stringify(obj) + "\n");
}
out.end();
// Python:
// import json
// with open("out.jsonl", "w") as f:
// for obj in records:
// f.write(json.dumps(obj) + "\n")
// One JSON per line; compact form (no indent) is conventional.Anwendungsfälle
JSONL glänzt bei Log-Dateien, großen Datensätzen, ML-Trainingsdaten, Datenbank-Dumps und append-only Event-Streams. Jede Zeile ist unabhängig, also kann man anhängen, ohne neu zu schreiben, das Parsen nach einer korrupten Zeile fortsetzen und parallel verarbeiten. Tools wie jq und Shell-Pipes arbeiten natürlich damit.
// JSONL is ideal for:
// - log files (one event per line)
// - large datasets (streaming, append-only)
// - machine learning training data
// - database exports/imports
// - append-only event streams
// Example: log entry per line
{"ts": "2024-01-15T10:00:00Z", "level": "info", "msg": "started"}
{"ts": "2024-01-15T10:00:01Z", "level": "error", "msg": "failed"}
// Tools: jq, xargs, awk | json.loads — all work line-by-line.JSONL vs. JSON-Array
Ein JSON-Array umwickelt Datensätze in [ ] und verlangt das Laden (oder sorgfältige Streaming) der ganzen Datei zum Parsen. JSONL setzt einen Datensatz pro Zeile und ermöglicht echtes Streaming, leichtes Anhängen und Erholung von korrupten Zeilen. Bei großen oder wachsenden Datensätzen ist JSONL fast immer die bessere Wahl.
// JSON Array (one big file):
[
{"name": "Alice"},
{"name": "Bob"},
{"name": "Carol"}
]
// JSONL (one per line):
{"name": "Alice"}
{"name": "Bob"}
{"name": "Carol"}
// JSON Array: must load whole file to parse; hard to append.
// JSONL: streamable, appendable, resumable; slightly more
// per-record overhead but far better for big files.Sicherheit
JSONP-Risiken
JSONP umwickelt JSON mit einem JavaScript-Callback, sodass ein <script>-Tag Cross-Origin-Daten laden kann und die Same-Origin-Policy umgeht. Das ist gefährlich: jede Site kann die Antwort lesen, Callback-Injection ermöglicht XSS, und Anfragen tragen die Cookies des Opfers. Stattdessen CORS nutzen — JSONP ist Legacy und unsicher.
// JSONP (JSON with Padding) bypasses same-origin policy
// by wrapping JSON in a script callback:
callbackHandler({"secret": "data"});
// Loaded via <script src="https://api.example.com/data?callback=callbackHandler">
// RISKS:
// - Any site can include the URL and read the response.
// - XSS if the callback name is attacker-controlled.
// - CSRF: the request is made with the victim's cookies.
// MODERN ALTERNATIVE: use CORS instead of JSONP.
// JSONP is legacy—avoid it for new APIs.XSS-Prävention
In HTML-<script>-Tags eingebettetes JSON kann XSS verursachen: der String '</script>' beendet das Skript vorzeitig. Außerdem sind U+2028 und U+2029 (line/paragraph separators) gültig in JSON-Strings, brechen aber JavaScript. Beim Einbetten von JSON in HTML <, >, &, U+2028, U+2029 escapen, oder eine Bibliothek wie serialize-javascript nutzen.
// JSON itself is data, not executable—BUT embedding it in
// HTML can cause XSS if not careful.
// BAD: output JSON inside <script> without escaping:
// <script>
// var data = {"name": "</script><script>alert(1)</script>"};
// </script>
// GOOD: escape < and > (and &) when embedding in HTML:
const safe = JSON.stringify(data)
.replace(/</g, "\\u003c")
.replace(/>/g, "\\u003e")
.replace(/&/g, "\\u0026")
.replace(/\u2028/g, "\\u2028")
.replace(/\u2029/g, "\\u2029");
// Or use a library: js-xss, serialize-javascript.Prototype Pollution
Prototype pollution entsteht, wenn untrustetes JSON mit Keys wie '__proto__' oder 'constructor' in Objekte gemischt wird und Object.prototype vergiftet — es wirkt auf alle Objekte. Abwehr: Object.create(null) nutzen, gefährliche Keys blocken, Map für untrustete Daten bevorzugen und Merge-Bibliotheken aktuell halten.
// Merging untrusted JSON into objects can pollute prototypes:
const evil = JSON.parse('{"__proto__": {"isAdmin": true}}');
// BAD merge (Object.assign does NOT pollute, but some libs do):
// function merge(target, src) {
// for (const k in src) target[k] = src[k];
// }
// Attackers can set Object.prototype.isAdmin = true,
// affecting ALL objects.
// Defenses:
// - Use Object.create(null) for parsed objects.
// - Block keys like __proto__, constructor, prototype.
// - Use Map instead of plain objects for untrusted data.
// - Keep dependencies updated (some had merge() flaws).Injection via JSON
JSON selbst ist injektionsresistent, aber es per String-Verkettung aufzubauen ist gefährlich — Nutzer-Input kann aus der JSON-Struktur ausbrechen. Immer einen echten Serializer nutzen (JSON.stringify). Dasselbe gilt nachgelagert: parametrisierte SQL-Queries, execFile mit Argument-Arrays und HTML-escaping Template-Engines.
// JSON itself is not injectable, but building JSON by
// concatenation is dangerous:
// BAD: string concatenation
// const json = '{"name": "' + userInput + '"}';
// // userInput = '"); drop table; //' -> breaks out
// GOOD: always use a real serializer
const json = JSON.stringify({ name: userInput });
// For SQL: use parameterized queries, not JSON interpolation.
// For shell: use execFile with arg arrays, not string concat.
// For HTML: use textContent or a templating engine that escapes.DoS über große oder tiefe JSON
JSON-basiertes DoS: riesige Dateien erschöpfen den RAM, tiefe Verschachtelung überläuft den Parser-Stack, und pathologische Strukturen (das JSON-Analogon zu 'billion laughs') blähen kleinen Input auf. Abwehr: Request-Body-Größe am Proxy begrenzen, Parsing-Tiefe begrenzen, für großen Input Streaming-Parser nutzen und Timeouts setzen.
// Attackers can craft JSON to exhaust memory or CPU:
//
// 1. Huge file: 1 GB of '[1,1,1,...]' to exhaust RAM.
// 2. Deep nesting: '{"a":{"a":{"a":...}}}' (10000 levels)
// to overflow the parser's stack.
// 3. 'Billion laughs': nested entity expansion (XML-era,
// but JSON analogs exist with $ref in some libs).
// 4. Many keys: 10 million keys in one object.
// Defenses:
// - Cap request body size at the server/reverse proxy.
// - Limit parsing depth (Ajv, fast-json-parse options).
// - Use streaming parsers (stream-json, oboe) for big input.
// - Set timeouts on parsing.Sichere Parsing-Praxis
Sicheres JSON-Parsing: immer JSON.parse nutzen (nie eval), vor der Nutzung gegen ein Schema validieren (Ajv, jsonschema), Tiefe und Key-Zahl begrenzen, __proto__-Keys deaktivieren und untrusteten Input ggf. in einem Web Worker oder Sandbox parsen. JSON.parse selbst ist sicher vor Codeausführung; die Risiken liegen darin, wie man die geparsten Daten nutzt.
// 1. Validate with a schema before using untrusted JSON.
const Ajv = require("ajv");
const ajv = new Ajv({ allErrors: true });
const validate = ajv.compile(schema);
if (!validate(data)) throw new Error(ajv.errorsText(validate.errors));
// 2. Limit depth and key count when parsing.
// 3. Use reviver/replacer to coerce types safely.
// 4. Never eval() or Function('return ' + json) — use JSON.parse.
// 5. Disable dangerous features (e.g., __proto__ keys).
// 6. Parse untrusted JSON in a sandbox or worker if possible.
// JSON.parse is safe; eval is NOT.Best Practices & Tools
Schema first
APIs schema-first entwerfen: ein JSON Schema definieren, Sprach-Typen daraus generieren (typescript-json-schema, quicktype, jsonschema2pojo) und Anfragen/Antworten zur Laufzeit validieren. Das findet Vertragsverletzungen früh, ermöglicht Codegenerierung und dient als lebende Dokumentation.
// Define a JSON Schema before shipping an API.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["id", "name"],
"properties": {
"id": { "type": "integer" },
"name": { "type": "string", "minLength": 1, "maxLength": 100 }
},
"additionalProperties": false
}
// Generate types from the schema (TypeScript, Java, Go, ...).
// Validate both requests and responses against the schema.
// Publish the schema for clients (OpenAPI, JSON Schema).Konsistente Namensgebung
Eine Namenskonvention für Keys wählen und konsistent anwenden: camelCase (die meisten JSON-APIs und JS), snake_case (Python/Ruby-Backends, Google-APIs) oder PascalCase (.NET). Stilmix verwirrt. Unterscheiden sich Front und Back, an einer einzigen Grenze konvertieren statt im Schema zu mischen.
// Pick ONE naming convention and apply it everywhere.
// camelCase (most JSON APIs, JavaScript ecosystem):
{ "firstName": "Alice", "lastName": "Smith" }
// snake_case (Python/Ruby backends, many Google APIs):
{ "first_name": "Alice", "last_name": "Smith" }
// kebab-case (rare in JSON, common in URLs/config):
{ "first-name": "Alice" }
// PascalCase (rare in JSON keys, common in C#/.NET types):
{ "FirstName": "Alice" }
// Avoid mixing; convert at the boundary if the front/back differ.Versionierung
APIs vom ersten Tag versionieren: im URL-Pfad (/v1/), als Versionsfeld in der Payload, im Accept-Header (Medientyp) oder als Namespace (JSON-LD @context). Additive Änderungen (neue optionale Felder) sind meist non-breaking; bei entfernten/umbenannten Feldern oder geänderter Semantik die Version erhöhen.
// 1. Version in the URL path:
// https://api.example.com/v1/users
// 2. Version field in the payload:
{ "version": "1.0", "data": { ... } }
// 3. Accept header / media type:
// Accept: application/vnd.example.v1+json
// 4. Namespace the JSON (JSON-LD, JSON:API 'type'):
{ "@context": "https://schema.org/v1", ... }
// Plan for evolution: add optional fields freely, but bump
// the version for breaking changes (removed/renamed fields,
// changed semantics or types).Encoding (UTF-8)
UTF-8 ist der Default und die einzige weit empfohlene Kodierung für JSON. Dateien als UTF-8 ohne BOM speichern (manche Parser kommen damit nicht klar), Content-Type mit charset=utf-8 setzen und Content-Length in Bytes angeben. In Python ensure_ascii=False übergeben, damit Unicode-Zeichen lesbar bleiben statt \uXXXX-Escapes.
// Always use UTF-8 for JSON.
// - Save files as UTF-8 (no BOM).
// - Set Content-Type: application/json; charset=utf-8.
// - Set Content-Length in bytes (not characters).
// In Node.js:
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.end(JSON.stringify(data));
// In Python:
import json
with open("out.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False)
// ensure_ascii=False keeps Unicode readable in the file.Performance-Tipps
Für Performance: große JSON streamen (ijson, stream-json, Jackson streaming) statt zu puffern; schnelle Serializer nutzen (orjson, fast-json-stringify); kompakt übertragen und über HTTP mit gzip/brotli komprimieren; tiefe Verschachtelung und riesige Arrays vermeiden; geparste Ergebnisse cachen, um Neu-Parsen zu vermeiden.
// 1. Stream large JSON instead of buffering it all.
// - Node: stream-json, JSONStream
// - Python: ijson
// - Java: Jackson streaming API
// 2. Use a fast serializer:
// - Node: fast-json-stringify (schema-based), orjson (Python)
// - Compile serializers from a schema for hot paths.
// 3. Compact JSON for transmission; pretty only for humans.
// 4. Avoid deep nesting and huge arrays when possible.
// 5. Compress with gzip/brotli over HTTP (huge savings).
// 6. Cache parsed results; don't re-parse the same payload.Tools & Validatoren
Tools für die Arbeit mit JSON: Online-Validatoren (jsonlint.com, jsonschemavalidator.net), CLI-Tools (jq für Abfragen/Formatieren, jsonschema für Validierung), Editor-Support (VS Code und JetBrains haben eingebaute JSON- + Schema-Validierung) und Code-Generatoren (quicktype erzeugt TypeScript/Java/Go/usw.-Typen aus JSON oder einem Schema).
// Online validators:
// - https://jsonlint.com
// - https://jsonformatter.org
// - https://www.jsonschemavalidator.net
// CLI tools:
// - jq (filter, query, format JSON on the command line)
// - jaq (Rust jq clone, faster)
// - jsonschema (Python CLI for schema validation)
// - ajv (Node CLI/library for JSON Schema)
// Editor support:
// - VS Code: built-in JSON + schema validation
// - JetBrains: built-in JSON + schema support
// - vim/emacs: plugins available
// Schema tools:
// - quicktype (generate types from JSON)
// - typescript-json-schema
// - jsonschema2pojo (Java)Verwandte JSON-Snippets
Copy-paste ready code for common tasks.
Data Types
The seven JSON value types.
Nested Objects
Objects within objects for hierarchical data.
Arrays
Lists of mixed and homogeneous values.
Schema Validation
Validate structure with JSON Schema.
JSONPath
Query expressions for locating nodes.
Merge Patch (RFC 7386)
Partially update JSON documents.
JSON Pointer (RFC 6901)
Address a specific value by path.
Streaming (NDJSON)
Newline-delimited JSON for streaming.
Was this helpful?