JSONの "Unexpected token" エラーを直す
JSON.parse で SyntaxError: Unexpected token ... in JSON at position Nが出たときの原因を、position N の読み方から系統立てて解説します。
This guide explains why JSON.parsethrows "Unexpected token ... at position N" and walks through the most common causes (trailing commas, single quotes, undefined, BOM, NaN).
TL;DR
position Nはインデックス番号。エディタで該当位置に飛ぶとほぼ確実に原因が見える- 最頻出は 末尾カンマ、シングルクォート、
undefinedの混入 - 0番目で失敗するなら BOM か 空文字列 を疑う
1. position N の読み方 / How to read "position N"
position の N は、入力文字列の 0始まりのコードポイントインデックス。 改行・タブ・BOM も 1 文字としてカウントされます。VS Code なら Ctrl+G → 目的行へジャンプし、 列番号を N から換算すれば一発で特定できます。
N is a zero-based character index, counting newlines and BOM. Jump to it in your editor.
2. 代表的な原因と対処 / Common causes
| 症状 / Symptom | 原因 / Cause | 対処 / Fix |
|---|---|---|
Unexpected token , in JSON at position N | 末尾カンマ / Trailing comma | 最後のカンマを削除 / Remove it |
Unexpected token ' in JSON | シングルクォート / Single quotes | 全てダブルクォートに / Use double quotes |
Unexpected token u in JSON at position 0 | 値が undefined / Value is undefined | response ?? "null" で fallback |
Unexpected token in JSON at position 0 (不可視) | BOM / UTF-8 BOM | s.replace(/^\uFEFF/, "") |
Unexpected token N in JSON | NaN / Infinity を書いた / Non-JSON numbers | null に置換 / Replace with null |
Unexpected end of JSON input | 閉じ括弧不足 / Truncated | ログ切れなら再取得 / Re-fetch source |
3. 再発防止 / Prevention
- JSON は手書きせず
JSON.stringifyで生成する - VS Code の
.jsoncモードは末尾カンマを許容するが、JSON.parse には通らないことを意識 - API レスポンスは JSON Schema Validator で契約を固める
4. English summary
JSON.parse throws Unexpected token ... in JSON at position Nwhen the input contains something that isn't legal JSON. The position is a zero-based character index, counting newlines and BOM. The frequent offenders are trailing commas, single quotes, a literalundefined, a UTF-8 BOM at position 0, and NaN/Infinitywhich JSON doesn't allow. Jump to the index in your editor, identify the category, and apply the corresponding fix. For recurring issues, validate payloads with a JSON Schema.