SyntaxError: Unexpected end of JSON input in JavaScript (Fixed)

Small figure of Jason Voorhees

Uncaught SyntaxError: Unexpected end of JSON input

You might have encountered the error “Uncaught SyntaxError: Unexpected end of JSON input” when using JSON.parse().

The error looks like this on Google Chrome:

Uncaught SyntaxError raised in a promise
Uncaught SyntaxError raised in a promise

First of all, it’s not your code! What’s most likely wrong is the JSON string you’re trying to parse.

When “Unexpected end of JSON input” is raised, your code is probably parsing:

  • An empty string
  • An empty array
  • Or an incomplete (a.k.a malformed) JSON data

That said, the first thing to examine is the JSON data.

If you’re using Google Chrome (like me), you can click the link on the right-hand side of the error message. 

It’s usually in the form of VM: Script ID, e.g., VM:1

If the log is empty, you’re probably dealing with an empty string! Otherwise, you’ll see the JSON data with an indicator.

How to fix the Uncaught SyntaxError: Unexpected end of JSON input

When working with JSON-formatted data in JavaScript, we’re either working with locally defined JSON data or fetching it from an API.

But how can we resolve the issue?

When working with locally defined JSON data: If you’re parsing local JSON content, the first thing to do is to ensure the variable isn’t empty. Maybe the variable is truncated for some reason.

If it’s not, you can validate your JSON-formatted data with an online JSON validator like JSONLint. If your JSON content is malformed, you’ll find out here!

When working with a third-party JSON API: If you’re trying to parse a JSON API response, and you don’t have control over the back-end code, you can place your JSON.parse reference into a try/catch block – like so:

  • json-parse-try-catch.js
 try {
  const data = JSON.parse(jsonData);
  // Do something with the JSON data
} catch (err) {
  console.error(err);
}

 

Wrapping up

The "Uncaught SyntaxError: Unexpected end of JSON input" is a Syntax error usually raised when parsing empty or malformed JSON data. Fixing this issue is easy when dealing with locally-defined JSON data. 

If you don't have control over the back-end code generating the JSON data, a try/catch block would help you avoid the "Uncaught SyntaxError" error.

Additionally, you might find this Mozilla guide on JSON.parse to avoid other types of parse errors.

I hope this quick guide provided the answer you were looking for.

Thanks for reading.

Author photo

Hey 👋 I'm a software engineer, an author, and an open-source contributor. I enjoy helping people (including myself) decode the complex side of technology. I share my findings on Twitter: @lavary_

If you read this far, you can tweet to the author to show them you care. Tweet a Thanks

In this article:

Disclaimer: This post might contain affiliate links. I might receive a commission if a purchase is made. However, it doesn’t change the cost you’ll pay.