404 Not Found

404 Not Found


nginx

JavaScript JSON

JSON(JavaScript Object Notation)は軽量なデータ交換フォーマットです。標準化された配送箱のようなものだと考えてください。中身が何であっても、包装はユニバーサルな仕様に従うため、受取人は開封方法を正確に理解できます。フロントエンド/バックエンド間の通信、設定ファイル、ローカルストレージ... JSON はどこにでもあります。


JSON 構文ルール

JSON は JS オブジェクトリテラルにとても似ていますが、ルールはより厳密です。

ルール 説明
キーはダブルクォート必須 "name"name'name'
文字列値はダブルクォート必須 "hello"'hello'
末尾カンマ不可 {"a":1,}
値のタイプは限定 文字列、数値、真偽値、null、オブジェクト、配列
許可されないもの undefined、関数、コメント
JSON
{
  "name": "Alice",
  "age": 25,
  "skills": ["HTML", "CSS", "JS"],
  "address": {
    "city": "New York",
    "zip": "10001"
  },
  "active": true,
  "spouse": null
}
⚠️ JSON でシングルクォートは使えません!最も一般的な初心者の間違いは 'key''value' を書くことです。JS では有効ですが JSON では無効です。


JSON.stringify()

JSON.stringify() は JS の値を JSON 文字列に変換します。シリアライゼーションです。

HTML
<script>
JSON.stringify(value)
JSON.stringify(value, replacer)
JSON.stringify(value, replacer, space)
</script>
パラメータ 説明
value シリアライズする値
replacer フィルタまたは変換。関数または配列
space インデント。数値または文字列。整形表示用

例:シリアライゼーションとフォーマット

HTML
<div id="output" style="white-space: pre; font-family: monospace; padding: 10px; border: 1px solid #ccc;"></div>

<script>
const student = {
  name: 'Bob',
  age: 20,
  scores: [95, 88, 92],
  active: true,
  grade: undefined,
  birthday: new Date()
};

const output = document.getElementById('output');

const plain = JSON.stringify(student);
output.textContent = 'コンパクト出力:\n' + plain + '\n\n';

const pretty = JSON.stringify(student, null, 2);
output.textContent += '整形出力:\n' + pretty + '\n\n';

const filtered = JSON.stringify(student, ['name', 'scores'], 2);
output.textContent += 'name と scores のみ:\n' + filtered;
</script>
▶ 試してみよう
💡 注意:シリアライゼーション中、undefined、関数、Symbol は無視されます(オブジェクトのプロパティからは消え、配列では null になる)。Date オブジェクトは ISO 文字列に変換されます。


JSON.parse()

JSON.parse() は JSON 文字列を JS の値に戻します。デシリアライゼーションです。

HTML
<script>
JSON.parse(text)
JSON.parse(text, reviver)
</script>
パラメータ 説明
text JSON 文字列
reviver 各キーと値のペアに適用される変換関数

例:デシリアライゼーション

HTML
<div id="output" style="white-space: pre; font-family: monospace; padding: 10px; border: 1px solid #ccc;"></div>

<script>
const output = document.getElementById('output');

const jsonStr = '{"name":"Charlie","age":30,"hobbies":["reading","coding"]}';

const obj = JSON.parse(jsonStr);

output.textContent = '解析結果:\n';
output.textContent += '名前: ' + obj.name + '\n';
output.textContent += '年齢: ' + obj.age + '\n';
output.textContent += '趣味: ' + obj.hobbies.join(', ') + '\n\n';

const arr = JSON.parse('[1, 2, 3, 4, 5]');
output.textContent += '解析された配列: ' + arr + '\n';
output.textContent += '配列の合計: ' + arr.reduce(function(a, b) { return a + b; }, 0);
</script>
▶ 試してみよう

JSON と JS オブジェクトの比較

比較項目 JSON JS オブジェクト
本質 文字列(テキスト) メモリ内のデータ構造
キーのクォート ダブルクォート必須 省略可能(有効な識別子の場合)
値のタイプ 限定(6タイプ) 任意のタイプ
末尾カンマ 不可
コメント 不可 サポート(ツール経由)
💡 簡単な覚え方:JSON は「厳密な検証付きの JS オブジェクトの文字列バージョン」です。オブジェクトではなくテキストです。操作可能なオブジェクトにするには parse が必要です。

例:よくある JSON エラー

HTML
<div id="output" style="white-space: pre; font-family: monospace; padding: 10px; border: 1px solid #ccc;"></div>

<script>
const output = document.getElementById('output');

function tryParse(str, label) {
  try {
    JSON.parse(str);
    output.textContent += label + ': ✅ 成功\n';
  } catch (e) {
    output.textContent += label + ': ❌ ' + e.message + '\n';
  }
}

tryParse("{'name':'Tom'}", 'シングルクォートのキー');
tryParse('{"name":"Tom",}', '末尾カンマ');
tryParse('{"name":undefined}', 'undefined 値');
tryParse('{"name":"Tom"}', '有効な JSON');
tryParse('{"a":1,"b":2}', '有効な JSON(スペースなし)');
</script>
▶ 試してみよう
💡 最も一般的な JSON エラー3つ:シングルクォート、末尾カンマ、undefined。JSON の問題をデバッグする際は、ブラウザコンソールに JSON.parse() を貼り付けてください。エラーメッセージが正確な位置を指摘します。


📖 まとめ

  1. JSON は文字列ベースのデータフォーマット。キーはダブルクォート必須、末尾カンマ不可、値のタイプは限定
  2. JSON.stringify() はシリアライズ、JSON.parse() はデシリアライズ。逆の操作
  3. シリアライゼーション中、undefined、関数、Symbol は無視されるか null になる
  4. JSON.stringifyspace パラメータは出力を読みやすくし、replacer パラメータはフィールドをフィルタ
  5. 無効な JSON の解析は例外をスローする。常に try/catch で囲む

❓ よくある質問

Q JSON.stringify(NaN)null を返すのはなぜですか?
A JSON 仕様には NaNInfinity-Infinity がなく、シリアライゼーション中にすべて null になります。これらの値を保持する必要がある場合は、カスタム replacer 関数を使いましょう。
Q JSON.parse で JS オブジェクトリテラルを解析できますか?
A いいえ。JSON.parse('{}') は動作しますが、JSON.parse('{a:1}') はエラーをスローします。キーにダブルクォートがないためです。JSON の構文は JS オブジェクトリテラルより厳密です。
Q JSON にコメントを書けますか?
A 標準 JSON はコメントをサポートしていません。必要に応じて "_comment": "説明" のようなフィールドをワークアラウンドとして使えますが、正式な慣習ではありません。

📝 演習

  1. 基礎:3つの生徒オブジェクトの配列を作成し、JSON.stringify でフォーマットして出力してください(スペース2でインデント)。
  2. 中級safeParse(str) 関数を書きましょう。JSON.parsetry/catch で囲み、成功時は結果を、失敗時は null とエラーメッセージを返してください。
  3. チャレンジ:「ローカルメモ帳」を構築してください。prompt で入力を受け取り、JSON.stringifylocalStorage に保存し、ページ読み込み時に JSON.parse で読み込んで表示してください。
100%