JavaScriptのUnexpected end of JSON inputの直し方

​​JavaScript​Chromium,Node.js,トラブルシュート

SyntaxError: Unexpected end of JSON input は、JSON.parse() や fetch() の res.json() に渡った文字列が空だったか、JSON の途中で切れていたときに出るエラーです。JSON の値を読み終わる前に文字列が終わってしまった、という意味です。空のときに何を返すかを決めて、本文を読む前に空かどうかを確かめると、エラーは消えます。

削除の API を fetch() で呼んだら、削除はできているのにエラーになった、という場面や、中身が空の設定ファイルを読み込んだ場面で出ます。私は検証環境でこのエラーをわざと起こし、出たメッセージと、直すと消えることを確かめました。

補足

検証環境は Ubuntu 24.04、Node.js 22.23.4、Playwright 1.63.0 で起動した Chromium 153.0.8010.12(ヘッドレス)です。ブラウザーのエラーは Playwright で取り出しました。Chrome の DevTools の画面での見え方や、Firefox・Safari のメッセージは確かめていません。

空の文字列や、途中で切れた JSON で出る

まず、Node.js で JSON.parse() にいくつかの文字列を渡しました。

js
// JSON.parse に、空の文字列や途中で切れた文字列を渡す
const inputs = ['', ' ', '\n', '{"name":', '{"name":"neko"}'];
for (const text of inputs) {
  try {
    console.log(JSON.stringify(text), '→ 結果:', JSON.stringify(JSON.parse(text)));
  } catch (e) {
    console.log(JSON.stringify(text), '→', String(e));
  }
}

結果は次のとおりです。

text
"" → SyntaxError: Unexpected end of JSON input
" " → SyntaxError: Unexpected end of JSON input
"\n" → SyntaxError: Unexpected end of JSON input
"{\"name\":" → SyntaxError: Unexpected end of JSON input
"{\"name\":\"neko\"}" → 結果: {"name":"neko"}

空の文字列だけでなく、空白や改行だけの文字列でも同じエラーになりました。{"name": のように、値が来る前に終わっている文字列でも同じです。Chromium の中で ''・' '・'{"name":' を JSON.parse() に渡しても、メッセージは同じ SyntaxError: Unexpected end of JSON input でした。

MDN の JSON.parse() のページにあるとおり、JSON.parse() は、渡された文字列が正しい JSON でなければ SyntaxError を投げます。

204 No Content を res.json() で読むと出る

fetch() では、本文のない応答を res.json() で読んだときにも出ます。Node.js の node:http で、DELETE /api/items/1 に 204 No Content を返すサーバー(http://localhost:8080)を作りました。サーバーのコードのうち、この部分を抜き出します。

js
} else if (req.url === '/api/items/1' && req.method === 'DELETE') {
  // 削除に成功したら、本文なしの 204 No Content を返す
  res.statusCode = 204;
  res.end();

curl で見ると、ステータスだけが返り、本文はありません。

console
$ curl -s -i -X DELETE http://localhost:8080/api/items/1
HTTP/1.1 204 No Content
Date: Mon, 16 Nov 2026 23:01:20 GMT
Connection: keep-alive
Keep-Alive: timeout=5

MDN の 204 No Content の説明には、DELETE への 204 は「成功して、ほかに返す情報がない」という意味で、204 の応答は本文を含んではならない、と書かれています。この応答は正しいもので、サーバーの不具合ではありません。

画面では、ボタンを押すと次の関数で削除の API を呼びます(out は、結果を表示する <pre> の要素です)。

js
// 本文を確かめずに res.json() で読む
async function deleteItem() {
  const res = await fetch('/api/items/1', { method: 'DELETE' });
  const data = await res.json();
  out.textContent = JSON.stringify(data);
}

Chromium でボタンを押すと、次のエラーが出て、画面には何も表示されませんでした。

text
Uncaught (in promise) SyntaxError: Failed to execute 'json' on 'Response': Unexpected end of JSON input

JSON.parse() のときとは違い、前に Failed to execute 'json' on 'Response': が付きます。res.json() が、空の本文を JSON として読もうとして失敗しています。MDN の Response.json() のページにも、本文を JSON として解釈できないときは SyntaxError になると書かれています。

Node.js の fetch() で同じ API を呼んで res.json() を実行すると、メッセージは JSON.parse() と同じ形でした。

text
DELETE http://localhost:8080/api/items/1 204 → SyntaxError: Unexpected end of JSON input

ステータスが 200 でも、本文が空なら同じです。Content-Type: application/json と Content-Length: 0 を返す /api/empty を res.json() で読むと、Chromium でも Node.js でも、204 のときと同じメッセージが出ました。Content-Type が JSON になっていても、本文が空なら読めません。

本文を文字列で受け取り、空なら null にする

直し方は、本文をいったん res.text() で文字列として受け取り、空か、空白だけなら null を返し、そうでなければ JSON.parse() で読むことです。

js
// 本文が空なら null を返し、空でなければ JSON として読む
async function readJson(res) {
  const text = await res.text();
  if (text.trim() === '') return null;
  return JSON.parse(text);
}

async function deleteItemFixed() {
  const res = await fetch('/api/items/1', { method: 'DELETE' });
  const data = await readJson(res);
  out.textContent = `status: ${res.status} data: ${JSON.stringify(data)}`;
}

res.json() を readJson(res) に置き換えてボタンを押すと、エラーは出ず、画面に次のように表示されました。

text
status: 204 data: null

同じ readJson() で、本文が空の /api/empty を読むと status: 200 data: null、JSON を返す /api/items を読むと status: 200 data: {"items":["りんご","みかん"]} になりました。本文がある応答は、これまでどおり JSON として読めます。

ポイント

res.status === 204 だけを見て分ける書き方では、200 で本文が空の応答を防げません。本文の文字列が空かどうかで分けると、どちらも1つの関数で扱えます。

呼び出した側では、data が null になる場合も考えておきます。

空の設定ファイルを JSON.parse したときも同じ

ファイルの読み込みでも、同じエラーが出ます。0 バイトの settings.json を作り、Node.js で次のように読みました。

js
// 設定ファイルを読む(そのまま読む版)
import { readFileSync } from 'node:fs';

const text = readFileSync('settings.json', 'utf8');
const settings = JSON.parse(text);
console.log('theme:', settings.theme);

実行すると、次のように止まりました(ファイルの場所は /path/to/app に置き換えています)。

console
$ node read-settings.mjs
<anonymous_script>:1


SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at file:///path/to/app/read-settings.mjs:5:23
    at ModuleJob.run (node:internal/modules/esm/module_job:343:25)
    at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:681:26)
    at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:117:5)

Node.js v22.23.4

at file:///path/to/app/read-settings.mjs:5:23 の行が、JSON.parse() を呼んだ場所(5行目の23文字目)です。この例では、先頭の <anonymous_script>:1 の下の行に、JSON.parse() に渡した文字列がそのまま出ています。ここが空行なので、渡した文字列が空だったと分かります。

ファイルが空のときに初期値を使うようにすると、止まらなくなりました。

js
// 設定ファイルを読む(空なら初期値を使う版)
import { readFileSync } from 'node:fs';

const defaults = { theme: 'light' };
const text = readFileSync('settings.json', 'utf8');
const settings = text.trim() === '' ? defaults : JSON.parse(text);
console.log('theme:', settings.theme);

空のファイルでは theme: light と初期値が出て、{"theme":"dark"} を書いたファイルでは theme: dark と、ファイルの値が出ました。

一方、{"theme": のように途中で切れた中身のファイルでは、この版でも SyntaxError: Unexpected end of JSON input で止まりました。空ではないので、JSON.parse() に渡るためです。このときは、<anonymous_script>:1 の下の行に {"theme": と、途中で切れた中身が出ました。途中で切れた JSON は、空のときのように初期値で済ませてよいものではなく、ファイルが壊れていることを示しているので、エラーで止まるままにして、ファイルの中身を直します。

​Posted by 86