はじめに
基本の構造
JSON は 6 つのデータ型をサポートします:文字列、数値、真偽値、null、配列、オブジェクト。キーはダブルクォートの文字列でなければなりません。JSON は言語に依存せず、人間にも機械にも読みやすい形式です。
{
"name": "Alice",
"age": 30,
"isStudent": false,
"height": 1.65,
"nullValue": null,
"hobbies": ["reading", "coding", "music"],
"address": {
"city": "NYC",
"zip": "10001"
}
}JSON の構文ルール
JSON には厳密な構文があります:キーと文字列はダブルクォートのみ、要素はカンマで区切り、末尾のカンマは禁止です。文書全体が 1 つの JSON 値でなければなりません。標準の JSON にはコメントがありません — 必要なら前処理か JSON5 を使いましょう。
{
"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 JSONJSON のコメント
標準の JSON はコメントを禁じます。よくある回避策:'_comment' フィールドの追加(コードが無視する)、JSONC/JSON5 の使用(VS Code と多くのツールが対応)、または comment-json や JSON.minify のようなライブラリでパース前にコメントを剥ぎ取る。
// 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)空白と整形
文字列の外の空白は意味を持ちません — コンパクトな形と整形された形は同じ値にパースされます。コンパクトな JSON は帯域を節約し、整形された形式(2 スペースのインデントが一般的)は読みやすさと diff を助けます。ほとんどのシリアライザが「pretty」オプションを提供します。
// 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.拡張子と MIME タイプ
標準の拡張子は .json で、MIME タイプは application/json です。JSONC、JSON5、GeoJSON、NDJSON のようなバリアントには独自の慣例があります。エンコーディングは常に UTF-8 を使いましょう。BOM は推奨されません。
// 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 値のカテゴリ
JSON の値は 6 つの型に分かれます:文字列、数値、真偽値、null、配列、オブジェクト。配列とオブジェクトは構造化され(他の値を保持できる)、残りはプリミティブです。有効な JSON 文書は 1 つの値です — 通常はオブジェクトか配列ですが、裸の数値や文字列も 有効です。
// 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.データ型
文字列型
JSON の文字列はダブルクォートされた Unicode テキストです。よくあるエスケープ:\"(引用符)、\\(バックスラッシュ)、\/(スラッシュ)、\n、\t、\r、\b、\f、そして任意の Unicode 符号点には \uXXXX。文字列の区切りとしてシングルクォートは認められません。
{
"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.数値型
JSON の数値は IEEE 754 倍精度の部分集合に従います:整数、小数、科学表記(例:6.022e23)。先頭のゼロは禁止です(007 は無効)。NaN、Infinity、-Infinity は「有効ではありません」 — 必要なら null や文字列としてエンコードしましょう。
{
"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).真偽値型
JSON の真偽値はリテラルのキーワード true と false です(小文字、引用符なし)。引用符付きの 'true'/'false' は文字列です。JSON の構文レベルには 0/1 や yes/no を真偽値とする概念はありません — アプリのコードで変換しましょう。
{
"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 型
JSON の null は裸のキーワード null です(引用符なし)。値の意図的な不在を示します。null は、空文字列 ''、0、false、存在しないキーとは区別されることに注意しましょう。多くの言語が null を 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.配列型
JSON の配列は [ ] で囲まれた順序付きリストで、カンマ区切り、0 起点です。任意の JSON 値を保持でき、混在した型やネストした配列/オブジェクトも含みます。空の配列 [] も有効です。順序は保持され、意味を持ちます。
{
"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.オブジェクト型
JSON のオブジェクトは { } で囲まれた順序なしのキー/バリューのコレクションです。キーは一意なダブルクォートの文字列でなければならず、値は任意の JSON 型にできます。オブジェクトは概念的に順序なしですが、ほとんどのパーサが挿入順を保持します。正しさのために順序に頼ってはいけません。
{
"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.文字列
文字列の基本
JSON の文字列は、ダブルクォートされた Unicode 文字の並びです。スラッシュはエスケープできます(\/)が必要ではありません — <script> タグの中に JSON を埋め込むときに有用です。空の文字列も有効です。
{
"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.エスケープシーケンス
JSON がサポートするエスケープ:\"(引用符)、\\(バックスラッシュ)、\/(スラッシ ュ)、\b(バックスペース)、\f(フォームフィード)、\n(改行)、\r(キャリッジリターン)、\t(タブ)、\uXXXX(Unicode 符号点)。その他のバックスラッシュシーケンスはすべて無効です。
{
"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 文字
任意の Unicode 符号点には \uXXXX を使いましょう。U+FFFF を超える文字(多くの絵文字など)にはサロゲートペアが必要です:2 つの \u エスケープ。モダンなパーサは、文字列の中に生の UTF-8 文字を直接受け付けます — \uXXXX は主に安全性のためや、文字を打てないときのためのものです。
{
"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.文字列内の特殊文字
JSON の文字列の内側では、ダブルクォートとバックスラッシュは必ずエスケープしなければなりません(\" と \\)。他の特殊文字(HTML、SQL、正規表現)はそれぞれのルールに従いますが、JSON が要求するのは \" と \\(と制御文字)のエスケープだけです。リテラルのバックスラッシュは \\ と書きます。
{
"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 \\.複数行文字列(回避策)
JSON の文字列はリテラルの改行を含められません — \n としてエスケープする必要があります。複数行のコンテンツには、文字列に \n を埋め込むか、行文 字列の配列を使うか、複数行文字列をサポートする YAML や JSON5 のような形式へ切り替えましょう。エスケープされていないリテラルの改行は構文エラーです。
// 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)よくある文字列の落とし穴
よくある文字列のエラー:シングルクォートの使用、末尾のカンマの残置、内側のダブルクォートのエスケープ忘れ、\t/\n のエスケープの代わりにリテラルの制御文字(タブ/改行)の埋め込み。厳密なパーサはこれらすべてを拒否します。
// 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\"" }数値
整数と浮動小数点数
JSON には単一の数値型があり、整数と浮動小数点値をカバーします。構文レベルには独立した整数型はありません — 言語のバインディングが、値とライブラリに応じて大きな整数を int、long、float、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.科学表記
JSON は科学表記をサポートします:仮数の後に e か E と、省略可能な符号付きの指数(6.022e23 = 6.022 * 10^23)。e と E のどちらも受け付けます。科学データの非常に大きい/小さい数には不可欠です。
{
"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.数値の精度
JSON の数値は通常 IEEE 754 の double としてパースされるため 、2^53-1(9007199254740991)を超える整数は JavaScript で精度を失います。0.1 のような小数は正確に表現できません。金銭や任意精度の整数には、文字列としてエンコードし、コードでは Decimal/BigInteger 型を使いましょう。
{
"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.特殊な値(許可されない)
標準の JSON は NaN、Infinity、-Infinity を許しません。回避策:NaN には null を、Infinity は文字列としてエンコードするか、有限のセンチネル値を使いましょう。一部のシリアライザ(Python の json のデフォルト、JSON5)はこれらを拡張として出力しますが、出力は非標準で、厳密なパーサに拒否され得ます。
// 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.数値の形式
有効な JSON の数値:省略可能なマイナス、整数部(0 を除き先頭のゼロは禁止)、省略可能な小数部、省略可能な指数。hex(0x)、binary(0b)、8 進、アンダースコア、先頭の +、先頭のゼロ、両側に数字のないドットは、すべて無効です。
// 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 // underscores大きな数値と BigInt
2^53-1 を超える値(Twitter の snowflake ID、64 ビット整数、大きな残高など)には、精度喪失を避けるため文字列としてエンコードしましょう。JSON.parse で数値を BigInt へ変換する reviver を使うなら、BigInt は replacer なしでは JSON.stringify で再シリアライズできないことを忘れないでください — ワイヤ上では文字列の方が安全です。
{
"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.真偽値と Null
真偽値
JSON の真偽値は裸のキーワード true と false です。引用符付きの 'true'/'false' は文字列です。JSON の構文レベルには truthy/falsy の概念はありません — 1、0、yes、no、on、off はすべて文字列か数値であり、真偽値ではありません。アプリのコードで変換しましょう。
{
"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.Null の意味
JSON の null は、値の意図的な不在を示します。存在しないキー(オブジェクトにキーがない)、空文字列 ''、0、false、空のコレクションとは区別されます。フィールドが存在するが値がないときは null を使い、フィールド自体が適用されないときはキーを省きましょう。
{
"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、空、欠落の区別
3 つの異なる状態:空の値を持つキー("")、明示的に null のキー、存在しないキーです。JavaScript では、undefined がキーの不在を意味し、null は存在するが値がないことを意味します。API は、省略可能なフィールドについてどの慣例を使うか文書化すべきです。
{
"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.条件式での真偽値の利用
JSON の真偽値を消費するとき、false と欠落を区別する必要があるなら、truthy チェックより厳密な比較(=== true)を推奨しましょう。API のレスポンスでは、false であっても真偽値のフィールドは必ず含めましょう — 省略すると、クライアントがデフォルトを推測させられます。
{
"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.よくある落とし穴
よくある落とし穴:true/false/null を引用符で囲むと文字列になります。True/TRUE/None(Python)や、大文字小文字の誤った true/false は無効です。JSON には undefined がありません(null だけです)。有効な形式は、小文字で引用符なしのキーワード true、false、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 }配列
配列の基本
JSON の配列は、[ ] で囲まれた順序付きの 0 起点リストで、値はカンマ区切りです。空の配列と 1 要素の配列も有効です。順序は意味を 持ち、パーサが保持します。末尾のカンマは許されません。
{
"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.混在型の配列
JSON の配列は混在した型を合法的に保持できます([1, 'two', true, null])。有効ですが、しばしば弱いスキーマ設計を示します。均質な配列(すべて文字列、すべてオブジェクト)の方が、検証、文書化、消費が容易です。要素型の強制にはスキーマを使いましょう。
{
"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.ネストした配列
配列は任意の深さにネストでき、行列、グリッド、ツリー構造に有用です。JSON はネストした配列が等しい長さであることを強制しません(「でこぼこ」の配列も有効です)。長方形の行列が必要なら、スキーマかアプリのコードで強制しましょう。
{
"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.オブジェクトの配列
オブジェクトの配列が、レコードのリスト(ユーザー、製品、投稿)の最もよくあるパターンです。各要素は通常同じ形状ですが、JSON はこれを強制しません — すべての要素が準拠するよう、スキーマ(JSON Schema の 'items')で検証しましょう。
{
"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.空配列と 1 要素配列
空の配列 [] と 1 要素の配列も有効です。API 設計では、[](存在するが空のリスト)と、null(存在するがリストなし)と、存在しないキー(フィールドが適用されない)を区別しましょう。「アイテムなし」に [] を返す方が、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 keyコード での配列アクセス
パース後、JSON の配列は、あなたの言語のネイティブな配列/リストになります(JS の Array、Python の list、Java の List など)。標準のインデックスアクセス、長さ、反復を使いましょう。境界と型の安全はあなたの責任です — JSON 自体は要素型を強制しません。
{
"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"]) # 3オブジェクト
オブジェクトの基本
JSON のオブジェクトは、{ } で囲まれた順序なしのキー/バリューのペアのコレクションです。キーはダブルクォートの文字列でなければならず、値は任意の JSON 型にできます。ペアはカンマ区切りで、末尾のカンマは禁止です。オブジェクトが、最もよくあるトップレベルの JSON 構造です。
{
"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).キーの命名ルール
JSON のキーは、空、スペース、ドット、数字を含む任意のダブルクォート文字列にできます。しかし API の明快さのため、一貫した camelCase、snake_case、kebab-case を推奨しましょう。公開 API では、スペース、ドット(パス構文との衝突)、空のキーは避けましょう。
{
"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.ネストしたオブジェクト
オブジェクトは任意の深さにネストでき、階層データに有用です。深いネストは有効ですが、読みやすさを損ない結合を増やし得ます。公開 API では、より平坦な構造を推奨するか、深くネストしたツリーの代わりに参照(ID)を使いましょう。
{
"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.配列を含むオブジェクト
オブジェクト(キー付きのフィールド用)と配列(順序付きリスト用)の組み合わせが、ほとんどすべての実世界のデータをモデル化します。よくあるパターンは、ネストしたオブジェクトの配列を包むオブジェクトです(注文を持つユーザー)。期待する形状の文書化と検証にはスキーマを使いましょう。
{
"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.メンバーの順序
JSON の仕様はオブジェクトを順序なしとして扱います。実際には、ほとんどのモダンなパーサ(JavaScript V8、Python 3.7+、Java の LinkedHashMap)が挿入順を保持しますが、正しさのためにこれに頼るべきではありません。ハッシュや署名のために順序が重要なら、キーを明示的にソートしましょう。
{
"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())重複するキー
JSON の仕様は重複するキーを禁じていませんが、その挙動は未定義です — ほとんどのパーサは最後の値を保持し、一部は最初の値を保持します。重複するキーが、微妙なバグのよくある原因です 。JSON Schema は uniqueKeys を強制でき、リンターと厳密なパーサは拒否できます。
// 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).ネストした構造
深いネスト
JSON は任意のネストの深さを許しますが、非常に深い構造は読みやすさを損ない、パーサの限界に当たることがあります(DoS を防ぐため、多くは深さの上限、例えば 1000 を課します)。深く階層的なデータには、ID/参照を使ったより平坦な構造を推奨しましょう。
{
"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.実世界の例
実世界の JSON は、エンティティとその関係をモデル化するため、オブジェクトと配列を混ぜます。この注文の例は、customer、items(オブジェクトの配列)、shipping をネストしています。形状の文書化にはスキーマを使い、読みやすさのためネストは控えめに保ちましょう。
{
"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
}
}ツリー構造
ツリーは再帰的にモデル化されます:各ノードが値と子ノードの配列を持ちま す。このパターンは、ファイルシステム、組織図、AST に現れます。循環に注意しましょう — JSON には参照の構文がないため、循環グラフは ID を使うか、親ポインタ付きのフラットなリストとしてシリアライズしなければなりません。
{
"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.ネストした値へのアクセス
深くネストした値へのアクセスは、中間のキーが欠けていると TypeError/KeyError のリスクがあります。省略可能なチェーン(JS の ?. と ??)や、デフォルト付きのチェーンした .get()(Python)を使いましょう。lodash.get や jq のようなライブラリが、深い抽出を単純化しデフォルトを提供します。
{
"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.ネストしたデータの平坦化
ネストしたオブジェクトの平坦化({ user: { name } } の代わりに 'user.name')により、環境変数、フォームフィールド、検索インデックスへのアクセスが簡単になります。トレードオフは、構造の喪失と、往復の困難さです。平坦化/非平坦化にはライブラリ(flat、lodash)を使いましょう。
// 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
スキーマの基本
JSON Schema は、JSON 文書を記述し検証するための JSON の語彙です。ルートが $schema(ドラフトのバージョン)と type を宣言します。Properties がフィールドと型を列挙し、required が必須のキーを列挙します。Ajv(JS)や jsonschema(Python)のようなバリデータが準拠を確認します。
{
"$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"]
}型の検証
'type' キーワードが、値の JSON 型を検証します:string、number、integer、boolean、null、array、object。単一の型でも配列でも構いません(省略可能な nullable な文字列には ['string', 'null'])。'integer' は小数部のない数値に一致します。
{
"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.文字列の制約
文字列の制約:minLength、maxLength、pattern(正規表現)、enum(許可された値)、format('email'、'uri'、'date-time'、'ipv4' のような意味的なヒント)。'format' はデフォルトでは注釈のみです — バリデータは強制のためオプトインしなければなりません。厳密な正規表現検証には pattern を使いましょう。
{
"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.数値の制約
数値の制約:minimum、maximum(含む)、exclusiveMinimum、exclusiveMaximum、multipleOf です。'integer' 型では、値は小数部を持ってはいけません。範囲をモデル化するには制約を組み合わせましょう(1〜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.オブジェクトと配列の制約
配列の制約:items(要素のスキーマ)、minItems、maxItems、uniqueItems です。オブジェクトの制約:required(必須のキー)、properties(フィールドのスキーマ)、additionalProperties(余分なキーの禁止には false、またはそのためのスキーマ)、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.高度な検証
高度な JSON Schema:oneOf/anyOf/allOf がサブスキーマを組み合わせ、$ref が再利用可能な定義を参照し、if/then/else が条件付きの検証を適用し、const が正確な値を要求し、enum が許可された値を列挙します。これらで、豊かな制約と再利用可能な型が表現できます。
{
"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 の構文
JSONPath は XPath に着想を得た、JSON のクエリ言語です。'$' がルートで、'.' が子を選択し、'[index]' が配列の要素を選択し、'*' がワイルドカード、'..' が再帰的下降です。jsonpath-plus(JS)や jsonpath-ng(Python)のようなライブラリが実装しています。
// 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 storeルートと子
'$' がルートを参照します。'.' が名前で子を選択し、'[]' が括弧の代替で、ドット、スペース、引用符を含むキーを扱えます。'[index]' が配列の要素を選択します(0 起点)。末尾から数える負のインデックスをサポートする実装もあります。
// '$' = 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']再帰的下降
'..'(再帰的下降)が、任意の深さのキーや要素に一致します。'$..price' が、どこに現れてもすべての 'price' の値を返します。'$..*' がすべてのノードを返します。正確なパスを知らずに、大きな、または深くネストした JSON を検索するのに非常に有用です。
{
"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 nestedフィルタ式
フィルタは [?(expression)] の形で、'@' が現在のアイテムを指します。対応する演算子は実装によって異なりますが、通常は ==、!=、<、<=、>、>=、&&(and)、||(or)を含み、時には正規表現の =~ もあります。length() や contains() のような関数が力を加えます。
// 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()ワイルドカード
'*' は、オブジェクトのすべての子か、配列のすべての要素に一致するワイルドカードです。'$.users[*].name' がすべてのユーザーの 'name' を返します。'$..*' がすべてのノードを返します。結果は一致の配列として返されます(1 つだけでも)。
{
"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.よくある関数と例
JSONPath の関数は実装によって異なります:length()、min()、max()、avg()、sum()、contains()、matches() がよくあります。フィルタと再帰的下降を組み合わせれば強力なクエリになります。CLI 作 業には、jq が事実上の標準で、わずかに異なる構文を使います。
// 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 対 XML・YAML
JSON と XML の構文比較
JSON はより軽量です(閉じタグがなく、数値/真偽値/null のネイティブ型があり、ほとんどの言語のデータ構造へ直接マッピングします)。XML はより重いですがリッチです:属性、名前空間、混合コンテンツ、スキーマ(XSD)、変換(XSLT)。Web API では JSON が支配的で、XML はエンタープライズ/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 と YAML の構文比較
YAML は波括弧/引用符の代わりにインデントを使い、コメント、複数行文字列、アンカー/エイリアスをサポートします。JSON はより厳密です(引用符が必須、コメントなし)が、より速く遍在しています。YAML は JSON のスーパーセットです — すべての有効な JSON ファイルは有効な 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 から YAML への変換
YAML は JSON のスーパーセットであるため、JSON から YAML への変換は単純で す。Python の yaml.dump と Node の js-yaml が処理します。結果はインデントを使い、(ほとんど)引用符を使いません。YAML のコメントと複数行文字列は、JSON からの往復では再現されません(JSON にはないため)。
// 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 から JSON への変換
YAML から JSON への変換は単純な YAML では機能しますが、YAML 固有の機能が失われます:コメント、アンカー/エイリアス、複数文書のストリーム、タグ、複雑なキー。カスタムタグからの任意コード実行を避けるため yaml.safe_load を使いましょう。結果は標準の 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.データモデリングの違い
JSON はデータをオブジェクトと配列としてモデル化します — 属性や名前空間はありません。XML は属性、名前空間、混合コンテンツ、リッチなスキーマを加えます。YAML はコメント、アンカー、複数文書の対応を加えます。TOML はテーブルによる設定ファイルを狙います。ニーズに基づき選びましょう:API は JSON、文書は XML、設定は 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.各形式の使いどころ
Web API と NoSQL ストレージには JSON(普遍的で高速)。エンタープライズのサービス、文書中心のデータ(SVG、XHTML)、リッチなスキーマには XML。人間が書く設定(CI/CD、docker-compose)には、コメ ントと読みやすさのため YAML。小さな設定ファイルには TOML。ユースケースに形式を合わせましょう。
// 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)JavaScript でのパース
JSON.parse
JSON.parse が JSON 文字列を JavaScript の値へ変換します。任意の有効な JSON 値(オブジェクト、配列、文字列、数値、真偽値、null)を受け付けます。無効な JSON は SyntaxError を投げます。信頼できない入力を扱うときは、JSON.parse を必ず try/catch で包みましょう。
// 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 が JavaScript の値を JSON 文字列へ変換します。関数、Symbol、undefined は(オブジェクトでは)省かれ、(配列では)null へ変わります。BigInt は TypeError を投げます — 先に文字列へ変換しましょう。整形には第 3 引数(スペース)を使いましょう。
// 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 関数
JSON.parse の reviver が、パース中に値を変換します。すべてのキー/バリューのペアに対して(ルートも含め、キー '' で)ボトムアップに呼ばれます。変換後の値を返すか、プロパティを省くには undefined を返します。日付のパース、BigInt、カスタム型に有用です。
// 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 関数
JSON.stringify の replacer が、シリアライズ中に値をフィルタ・変換します。関数としてなら、すべてのキーに対して呼ばれ — プロパティを省くには undefined を返します。配列としてなら、含めるキーの許可リストとして機能します。シークレットの墨消しやフィールドの選択に有用です。
// 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}'整形出力
整形出力には、JSON.stringify へスペース引数を渡しましょう:数値(インデントの深さ)か文字列('\t' など)。安定したキー順(ハッシュや署名に有用)には、文字列化の前にキーをソートしましょう。整形しつつフィールドをフィルタするには、replacer と組み合わせます。
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);エラー処理
JSON.parse は無効な入力で SyntaxError を投げます — 信頼できないデータでは必ず try/catch で包みましょう。よくある原因:末尾のカンマ、シングルクォート、コメント、切り詰められた入力です。非常に大きい、または深くネストした JSON には、DoS を防ぐためストリーミングパーサか深さの制限を検討しましょう。
// 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.Python でのパース
json.loads
json.loads が JSON 文字列を Python のオブジェクトへパースします。JSON のオブジェクトは dict、配列は list、文字列は str、数値は自動的に int か float、true/false は True/False、null は None になります。'loads' は '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 が Python のオブジェクトを JSON 文字列へシリアライズします。整形には indent を、Unicode 文字を(\uXXXX エスケープの代わりに)保つには ensure_ascii=False を、安定した出力には sort_keys=True を使いましょう。Python の True/False/None が 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.ファイルのパース
ファイルには json.load(ファイルオブジェクト)と json.dump(ファイルオブジェクト)を、文字列には json.loads と json.dumps を使いましょう。プラットフォームのデフォルトを避けるため、ファイルは必ず encoding='utf-8' で開きましょう。大きなファイルには、より良いパフォーマンスのため ijson(ストリーミング)か orjson(高速)を検討しましょう。
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.カスタムエンコーダ
json.JSONEncoder を継承し default() をオーバーライドすれば、JSON がネイティブにサポートしない型(datetime、set、Decimal、カスタムクラス)をシリアライズできます。JSON でシリアライズ可能な表現を返しましょう。デコードには、変換を逆にするカスタムフック(object_hook)を書きます。
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.エラー処理
json.loads は無効な入力で json.JSONDecodeError を発生させ、行/列の情報を持ちます。よくある原因:末尾のカンマ、シングルクォート、コメント、NaN/Infinity(デフォルトで拒否)、文字列内の制御文字です。必要なら、NaN/Infinity/-Infinity の処理には parse_constant を使いましょう。
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 の扱い
デフォルトでは、json はすべての数値を float としてパースし、金銭のような小数の精度を失います。精度を保つには parse_float=Decimal を渡し、シリアライズには Decimal を戻すデフォルトフックを使いましょう(精度を保つには str へ、損失が許容されるなら float)。正確な金銭の表現には str を使いましょう。
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.Java でのパース
Jackson の基本
Jackson が最も人気のある Java の JSON ライブラリです。ObjectMapper.readValue が JSON を POJO へパースし、writeValueAsString がシリアライズします。依存として jackson-databind(jackson-core と jackson-annotations も)を加えましょう。Jackson は速く成熟しており、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 の基本
Gson は Google の JSON ライブラリで、基本的な使い方は Jackson より単純です。Gson.fromJson がパースし、toJson がシリアライズします。オプション(整形出力、null のシリアライズ、カスタムアダプタ)には GsonBuilder を使いましょう。依存として com.google.code.gson:gson を加えます。Gson は Android で一般的です。
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 ツリーモデル
Jackson の JsonNode は、POJO なしで JSON をたどるツリーモデルです。get()(欠けていれば null を返す)か path()(チェーンのため安全な「missing node」を返す)を使いましょう。asText/asInt/asBoolean はデフォルト値付きのオーバーロードを持っています。スキーマが未知か変化する場合に有用です。
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");カスタムデシリアライズ
カスタムの JsonDeserializer が、非標準の JSON エンコーディング(金銭の '$19.99' など)を扱います。フィールドに @JsonDeserialize(using = ...) を注釈するか、型のために SimpleModule を登録しましょう。カスタムのシリアライズには JsonSerializer を使います。これで POJO がパースロジックからきれいに保たれます。
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.ストリーミング API
Jackson のストリーミング API(JsonParser/JsonGenerator)が、一定のメモリでトークンごとに JSON を読み書きします — 巨大なファイルに理想的です。パースのループを制御でき、skipChildren() でサブツリーをスキップできます。実際に必要な部分には、ツリーか POJO モデルと組み合わせましょう。
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.PHP でのパース
json_encode
json_encode が PHP の値を JSON へシリアライズします。PHP の配列は、JSON のオブジェクト(連想)か配列(連続)になります。よくあるフラグ:JSON_PRETTY_PRINT、JSON_UNESCAPED_UNICODE(読める Unicode を保つ)、JSON_UNESCAPED_SLASHES(/ をエスケープしない)。フラグは | 演算子で組み合わせましょう。
<?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 が JSON を PHP へパースします。第 2 引数が結果を制御します:true なら連想配列、false(デフォルト)なら stdClass オブジェクトです。アクセスのスタイル($arr['key'] 対 $obj->key)に応じて選びましょう。連続でないキーを持つ PHP の配列は、JSON のオブジェクトになります。
<?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.エラー処理
PHP の json_decode はデフォルトでは投げません — パース後に json_last_error() と json_last_error_msg() を確認しましょう。JSON_THROW_ON_ERROR(PHP 7.3+)を渡せば、よりきれいに JsonException を投げます。よくあるエラー:末尾のカンマ、シングルクォート、無効な 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();
}整形出力とフラグ
よくある json_encode のフラグ:JSON_PRETTY_PRINT(インデント)、JSON_UNESCAPED_UNICODE(読める非 ASCII を保つ)、JSON_UNESCAPED_SLASHES(/ をエスケープしない)、JSON_NUMERIC_CHECK(数値文字列を数値へ変換)、JSON_THROW_ON_ERROR(失敗時に投げる)。| で組み合わせましょう。
<?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}カスタムシリアライズ
JsonSerializable を実装し jsonSerialize() を定義すれば、オブジェクトのエンコード方法を制御できます。これが、フィールドの墨消し(パスワードの省略など)、キーの改名、シリアライズ中の派生値の計算のための最もきれいな方法です。メソッドは JSON でシリアライズ可能な任意の構造を返します。
<?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 仕様
文書の構造
JSON:API は、一貫した JSON API を構築するための仕様です。文書は、トップレベルの 'jsonapi' バージョンオブジェクト、主要な 'data' リソース、省略可能な 'included' 関連リソース、非標準情報のための 'meta'、ページネーションのための 'links'、失敗のための 'errors' を持ちます。メディアタイプは 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.リソースオブジェクト
JSON:API のリソースオブジェクトは、'type'(リソースの種類)と 'id'(文字列の識別子)を持ち、加えて 'attributes'(データ)と省略可能な 'relationships'(他のリソースへのリンク)と 'links'(self のような URL)を持ちます。ID は文字列でなければなりません。type と id が attributes に現れてはいけません。
{
"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.リレーションシップ
リレーションシップが、リソース識別子オブジェクト({type, id})を経由して、リソースを他と結びます。to-one のリレーションシップは単一の識別子を、to-many は配列を使います。'links' オブジェクトが、ナビゲーションのため 'self'(リレーションシップの URL)と 'related'(関連リソースの URL)を提供します。
{
"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' が、合計数、レート制限、警告のような非標準の情報を運びます。'links' がハイパーメディアのナビゲーションを提供します:ページネーションのための self、first、prev、next、last、加えて関連 URL。存在しないリンク(最初のページの prev など)には null を使いましょう。
{
"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.Errors
JSON:API のエラー文書は、トップレベルの 'errors' 配列を持ちます('data' はありません)。各エラーオブジェクトには省略可能なフィールドがあります:id、status(文字列としての HTTP コード)、code(アプリ固有)、title(短い要約)、detail(人間向けの説明)、source(JSON Pointer 経由で不正なフィールドへのポインタ)、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 の機能
JSON5 は、人間が書く設定のために設計された JSON のスーパーセットです。コメント、引用符なし/シングルクォートの文字列、末尾のカンマ、hex/Infinity/NaN の数値、緩い数値形式を加えます。JSON5 は標準の JSON ではありません — JSON5 パーサ(json5 の npm パッケージ)を使い、交換のため JSON へ変換しましょう。
// 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.コメント
JSON5 は // 行コメントと /* */ ブロックコメントの両方をサポートします。標準の JSON はこれを禁じています。これで JSON5 は、人間が書く設定ファイルに理想的になります。VS Code の settings.json と TypeScript の tsconfig.json は JSONC(コメント付き JSON)を使います。似ているがわずかに異なる部分集合です。
{
// 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).末尾のカンマ
JSON5 は、オブジェクトと配列の最後の要素の後のカンマを許します。標準の JSON はこれを拒否します。末尾のカンマは、フィールドの追加や並べ替え時の diff のノイズを減らします(各行がカンマで終われます)。多くのモダンな言語と設定形式が今やこれを許しています。
{
"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.引用符なし・シングルクォート文字列
JSON5 は、引用符なしの識別子キー([A-Za-z_$][A-Za-z0-9_$]* に一致)と、シングルクォート・ダブルクォートの両方の文字列を許します。シングルクォートの文字列の内側では ' を \' とエスケープし、ダブルクォートでは " を \" とエスケープします。これは、読みやすさのため JavaScript のオブジェクトリテラル構文を反映しています。
{
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.数値と文字列(拡張)
JSON5 は数値を拡張します:16 進(0xFF)、先頭/末尾の小数点(.5、5.)、先頭のプラス(+5)、キーワードの Infinity、-Infinity、NaN。これらはすべて標準の JSON では拒否されます。JSON5 の文字列は依然、改行にエスケープシーケンス(\n)を使います — 裸の複数行文字列はありません。
{
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 の形式
JSON Lines(JSONL か NDJSON)は、各行が独立した完全な JSON 値である形式です。囲む配列はありません。これが、ストリーミング、ログ、大きな dataset に理想的になります:ファイル全体をロードせずに行ごとに処理できます。拡張子:.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 の読み取り
JSONL の読み取りは、行を反復し、各行を JSON.parse/loads でパースします。これが一定のメモリでファイルをストリーミングします — 巨大な dataset に理想的です。空行はスキップしましょう。Node.js では、ファイルストリーム上の readline を使い、Python ではファイルオブジェクトを直接反復します。ファイル全体のロードは不要です。
// 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 の書き込み
JSONL の書き込みは、各レコードを JSON.stringify/dumps で(コンパクト、インデントなし)シリアライズし、改行を追記します。効率のため、書き込み可能なストリーム(Node)か書き込みモードで開いたファイル(Python)を使いましょう。コンパクトな形式が行を短くパース可能に保ち、1 行 1 レコードがルールです。
// 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.ユースケース
JSONL が輝くのは、ログファイル、大きな dataset、ML の学習データ、データベースのダンプ、追記のみのイベントストリームです。各行が独立しているため、書き直さずに追記でき、破損した行の後でパースを再開でき、並列に処理できます。jq やシェルパイプのようなツールが自然に機能します。
// 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 と JSON 配列の比較
JSON の配列はレコードを [ ] で包み、パースのためファイル全体をロードする(または慎重にストリーミングする)必要があります。JSONL は 1 行に 1 レコードを置き、本物のストリーミング、簡単な追記、破損した行からの回復を可能にします。大きい、または成長する dataset には、JSONL がほとんど常に良い選択です。
// 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.セキュリティ
JSONP のリスク
JSONP は JSON を JavaScript のコールバックで包み、<script> タグが同一オリジンポリシーをバイパスしてクロスオリジンのデータを取得できるようにします。これは危険です:任意のサイトがレスポンスを読め、コールバックの注入が XSS を可能にし、リクエストが被害者の Cookie を運びます。代わりに CORS を使いましょう — JSONP はレガシーで安全ではありません。
// 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 の予防
HTML の <script> タグに埋め込まれた JSON は XSS を引き起こせます:文字列 '</script>' がスクリプトを早期に終わらせるからです。また、U+2028 と U+2029(行/段落の区切り)は JSON の文字列では有効ですが、JavaScript を壊します。HTML に JSON を埋め込むときは <、>、&、U+2028、U+2029 をエスケープするか、serialize-javascript のようなライブラリを使いましょう。
// 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.プロトタイプ汚染
プロトタイプ汚染は、'__proto__' や 'constructor' のようなキーを含む信頼できない JSON がオブジェクトへマージされるときに起きます。Object.prototype が汚染され、すべてのオブジェクトに影響します。防御:Object.create(null) の使用、危険なキーのブロック、信頼できないデータには Map の使用、マージライブラリの更新の維持。
// 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).JSON 経由のインジェクション
JSON 自体はインジェクションに耐えますが、文字列連結による構築は危険です — ユーザー入力が JSON 構造から脱出できます。本物のシリアライザ(JSON.stringify)を必ず使いましょう。下流も同様です:パラメータ化された SQL クエリ、引数配列付きの execFile、HTML エスケープするテンプレートエンジンを使いましょう。
// 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.巨大・深い JSON による DoS
JSON ベースの DoS:巨大なファイルが RAM を使い尽くし、深いネストがパーサのスタックを溢れさせ、病的な構造(「billion laughs」の JSON 版)が小さな入力を膨らませます。防御:プロキシでリクエストボディのサイズに上限、パースの深さの制限、大きな入力へのストリーミングパーサ、タイムアウトの設定。
// 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.安全なパースの実践
安全な JSON パース:必ず JSON.parse を使い(eval は決してしない)、使う前にスキーマ(Ajv、jsonschema)で検証し、深さとキー数に上限を設け、__proto__ キーを無効化し、信頼できない入力のパースは Web Worker かサンドボックスで検討しましょう。JSON.parse 自体はコード実行から安全です。リスクは、パースされたデータの使い方にあります。
// 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.ベストプラクティスとツール
スキーマファースト
API はスキーマファーストで設計しましょう:JSON Schema を定義し、そこから言語の型を生成し(typescript-json-schema、quicktype、jsonschema2pojo)、リクエスト/レスポンスを実行時に検証します。これで契約違反が早期に捉えられ、コード生成が可能になり、生きたドキュメントになります。
// 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).一貫した命名
キーの命名規則を 1 つ選び、一貫して適用しましょう:camelCase(ほとんどの JSON API と JS)、snake_case(Python/Ruby のバックエンド、Google の API)、PascalCase(.NET)。スタイルの混在は混乱を招きます。フロントとバックが異なるなら、スキーマで混ぜるのではなく、単一の境界で変換しましょう。
// 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.バージョニング
API のバージョニングは最初の day から始めましょう:URL パス(/v1/)、 ペイロードのバージョンフィールド、Accept ヘッダー(メディアタイプ)、名前空間(JSON-LD の @context)。追加的な変更(新しい省略可能なフィールド)は通常破壊的ではありません。フィールドの削除・改名や意味の変更には、バージョンを上げましょう。
// 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).エンコーディング(UTF-8)
UTF-8 が、JSON のデフォルトで唯一広く推奨されるエンコーディングです。ファイルは BOM なしの UTF-8 で保存し(誤って扱うパーサがあります)、Content-Type に charset=utf-8 を設定し、Content-Length はバイトで設定しましょう。Python では、\uXXXX エスケープの代わりに Unicode 文字を読めるまま保つため、ensure_ascii=False を渡しましょう。
// 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.パフォーマンスのヒント
パフォーマンスのために:大きな JSON はバッファリングではなくストリーミングし(ijson、stream-json、Jackson のストリーミング)、速いシリアライザを使い(orjson、fast-json-stringify)、コンパクトに送り、HTTP 上で gzip/brotli で圧縮し、深いネストと巨大な配列を避け、再パースを避けるためパース結果をキャッシュしましょう。
// 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.ツールとバリデータ
JSON を扱うツール:オンラインのバリデータ(jsonlint.com、jsonschemavalidator.net)、CLI ツール(クエリ/整形の jq、検証の jsonschema)、エディタの対応(VS Code と JetBrains は JSON + スキーマ検証が組み込み)、コードジェネレータ(quicktype が JSON かスキーマから TypeScript/Java/Go などの型を生成)。
// 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)関連する JSON スニペット
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?