More JavaScript answers

by Danny
Published 2 min read

JSON.parse throws "Unexpected end of JSON input" when the text is empty or cut short. Learn why it happens with fetch and storage, and how to parse JSON safely.

The short answer

#

JSON.parse reached the end of the string before it had a complete value. Most of the time the string is empty: an API returned no body, localStorage had nothing saved, or a file was empty. Check the raw text before you parse it, and handle the empty case.


_10
const response = await fetch('/api/user');
_10
const text = await response.text();
_10
const data = text ? JSON.parse(text) : null;

Why it happens

#

JSON is strict. JSON.parse must see one complete value, such as an object, array, string, number, true, false or null. An empty string is not valid JSON, and neither is text that stops halfway through, such as {"name": "Ada" with no closing brace. When the parser runs out of characters, it throws this error.

The wording differs between engines. Chrome and Node say "Unexpected end of JSON input", Firefox says "JSON.parse: unexpected end of data", and Safari says "JSON Parse error: Unexpected EOF". They all mean the same thing.

Typical causes are:

  • Calling response.json() on a response with no body, such as a 204 No Content or a DELETE that returns nothing.
  • Calling response.json() on an error response from a server or proxy that sent an empty body.
  • Reading a missing key from storage. localStorage.getItem returns null, and JSON.parse(null) actually returns null, but an empty string saved earlier will throw.
  • A response that was cut off by a timeout, a crashed server or a file written halfway.

Its close cousin, "Unexpected token < in JSON at position 0", means the body was there but was HTML, usually an error page or the wrong URL. Newer engines phrase it as "is not valid JSON".

How to fix it

#

Check the response before parsing

Look at the status and the body before you treat it as JSON. This also catches HTML error pages.


_12
async function getJson(url) {
_12
const response = await fetch(url);
_12
_12
if (!response.ok) {
_12
throw new Error(`Request failed with ${response.status}`);
_12
}
_12
_12
if (response.status === 204) return null;
_12
_12
const text = await response.text();
_12
return text ? JSON.parse(text) : null;
_12
}

Reading the body as text first means you can log it when parsing fails, which makes the real problem obvious.

Wrap JSON.parse in try...catch

When the input comes from outside your code, such as storage, a file, a message or user input, expect that it might be invalid.


_10
function safeParse(text, fallback = null) {
_10
try {
_10
return JSON.parse(text);
_10
} catch (error) {
_10
console.warn('Invalid JSON:', text);
_10
return fallback;
_10
}
_10
}
_10
_10
const settings = safeParse(localStorage.getItem('settings'), {});

Fix the server so it sends valid JSON

If you own the API, make every JSON endpoint return a JSON body, including errors. Return null, {} or an error object rather than an empty body, and set the Content-Type: application/json header. Then clients do not need special cases for each endpoint.

Check the content type when you are not sure

For endpoints that sometimes return JSON and sometimes do not, check the header first.


_10
const type = response.headers.get('content-type') ?? '';
_10
const data = type.includes('application/json')
_10
? await response.json()
_10
: await response.text();

Common pitfalls

#
  • Parsing something that is already an object. JSON.parse turns its argument into a string first, so an object becomes "[object Object]" and fails with a different error.
  • Calling JSON.parse(undefined). It becomes the string "undefined", which is not valid JSON.
  • Building JSON by hand with string concatenation. Use JSON.stringify so quotes and special characters are escaped.
  • Reading a file in Node while another process is still writing it. Write to a temporary file and rename it, so readers never see half a file.
  • Swallowing the error silently. Log the raw text in the catch block, or you will not know what the server actually sent.
#

Was this resource helpful?