DEV Community

Cover image for About "SyntaxError: Unexpected end of JSON input" in JavaScript
Reza Lavarian
Reza Lavarian

Posted on • Originally published at

About "SyntaxError: Unexpected end of JSON input" in JavaScript

Update: This post was originally published on my blog, where you can read the latest version for a 💯 user experience. ~reza

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

The error looks like this on the browser console (Google Chrome):

Image description

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:

  1. An empty string
  2. An empty array
  3. 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 you have an invalid JSON object, 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:

try {
  const data = JSON.parse(jsonData);
  // Do something with the JSON data
} catch (err) {
Enter fullscreen mode Exit fullscreen mode

Wrapping up

The infamous "JSON input error" 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.

Top comments (0)