MeWrite Docs

SyntaxError: Unexpected token in JSON

JSONの構文が不正な場合に発生するパースエラー

概要

JSON.parse()で不正なJSON形式のデータをパースしようとした場合に発生するエラーです。

エラーメッセージ

SyntaxError: Unexpected token < in JSON at position 0
SyntaxError: Unexpected end of JSON input
SyntaxError: Unexpected token u in JSON at position 0

原因

  1. HTMLが返されている: APIがJSONではなくHTMLを返している
  2. 末尾のカンマ: 最後の要素の後にカンマ
  3. シングルクォート: JSONはダブルクォートのみ
  4. undefined/NaN: JSON非対応の値
  5. 空のレスポンス: 何も返されていない

解決策

1. レスポンスを確認してからパース

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
async function fetchData(url) {
  const response = await fetch(url);

  // Content-Typeを確認
  const contentType = response.headers.get('content-type');
  if (!contentType?.includes('application/json')) {
    const text = await response.text();
    console.error('Not JSON:', text.substring(0, 100));
    throw new Error('Response is not JSON');
  }

  return response.json();
}

2. try-catchでエラーハンドリング

1
2
3
4
5
6
7
8
9
function safeJsonParse(text) {
  try {
    return JSON.parse(text);
  } catch (error) {
    console.error('JSON parse error:', error);
    console.error('Input:', text.substring(0, 100));
    return null;
  }
}

3. JSON形式を修正

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// 悪い例
{
  'name': 'John',  // シングルクォート
  "items": [1, 2, 3,],  // 末尾カンマ
}

// 良い例
{
  "name": "John",
  "items": [1, 2, 3]
}

4. JSONバリデーション

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function isValidJSON(str) {
  try {
    JSON.parse(str);
    return true;
  } catch {
    return false;
  }
}

// オンラインツール
// https://jsonlint.com/

5. nullやundefinedをチェック

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function parseResponse(data) {
  if (data === null || data === undefined) {
    return null;
  }

  if (typeof data === 'string') {
    return JSON.parse(data);
  }

  return data;  // 既にオブジェクトの場合
}

6. APIエラーを処理

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
async function fetchJson(url) {
  const response = await fetch(url);

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
  }

  const text = await response.text();

  if (!text) {
    return null;  // 空のレスポンス
  }

  return JSON.parse(text);
}

7. JSONを整形してデバッグ

1
2
3
const obj = { name: 'John', age: 30 };
const json = JSON.stringify(obj, null, 2);
console.log(json);

JavaScript の他のエラー

最終更新: 2025-12-09