Skip to main content

How to Fix the JSON Parse Error in JavaScript

·4 mins
How to Fix the JSON Parse Error in JavaScript

There are two reasons why you might see the JSON parse error in your JavaScript code and, as a JavaScript developer, you need to know how to fix both of them.

So in this article I will show you when these two errors can occur and how you can fix them.

Watch the video tutorial here.

But first, let’s just quickly have a refresher on what JSON.parse does.

What does JSON.parse do? #

JSON Parse function

The JSON.parse function takes a string of JSON data and attempts to convert it to a JavaScript object or array so you can use the data within your code.

Problems occur when the string you pass to JSON.parse isn’t properly formatted JSON data or something completely different entirely which doesn’t even resemble JSON data. This is when you’ll get the error thrown by the JSON.parse function.

Providing your own bad JSON data to JSON.parse #

So the first reason you’ll get this error is if you provide your own string to the JSON.parse function which isn’t valid JSON.

const object = JSON.parse('not JSON data');
// Uncaught SyntaxError: JSON.parse: unexpected keyword at line 1 column 1 of the JSON data

You might get a slightly more specific error if you have JSON data that is just badly formatted.

JSON.parse(`{"key": "value }`) 
// Uncaught SyntaxError: JSON.parse: unterminated string at line 1 column 16 of the JSON data

The fix for this problem is simple - you just need to ensure the string you are passing to JSON.parse is valid JSON. If this is something that is hardcoded in your application then this should be a case of updating the string in your JavaScript code.

Of course, it’s unlikely you’ll be using JSON strings like this in your app code. It’s more likely you’ll be accepting this string as user input from a text input, for example if they user is providing some configuration details for you.

In these cases, you want to check that the user input is valid JSON and the best way to do this is to try and parse the JSON and catch any errors the function might through.

const userInputElement = document.getElementById('userInput');
let result;
try {
    result = JSON.parse(userInputElement.value);
} catch (error) {
    result = {};
}

What you do if an error is thrown is kinda up to you. I tend to set the expected result to be an empty object and then deal with missing data down the line but it depends what you’re taking the user input for and what it is going to be used for.

It might be worth creating a function to test if JSON input is valid and then you can alert the user to any validation problems before forms are submitted.

const isJSON = jsonStr => {
    try {
        JSON.parse(jsonStr);
        return true;
    } catch (error) {
        return false;
    }
}

Bad network calls (using Fetch API) #

It’s common to receive JSON data from network calls to APIs and 3rd party data sources but sometimes these network requests go wrong and either bad JSON or an error string are returned as the response.

The same principles apply as above but depending on what network client you’re using you might need to handle the error differently.

Here’s an example for the popular Fetch API.

 fetch(`${apiUrl}/bad`)
    .then(result => {
        console.log(result);

        if (!result.ok) {
            throw new Error(`Bad Response [${result.statusText}]`);
        }

        return result.json()
    })
    .then(json => { 
        document.getElementById('networkResult')
            .textContent = JSON.stringify(json, null, 2);
    })
    .catch(error => {
        console.error(error);
        document.getElementById('networkResult')
            .textContent = error;
    })

The Fetch API tries to parse the response for the network request using the .json() function which will throw an error if the response isn’t JSON for whatever reason.

There are several things that you can check on the result that is returned from the network request. In the example above I am just checking if the result.ok property is falsy and then throwing a new error (to be picked up by the catch block below) with a customised error.

If result.ok is truthy, we try and parse the JSON data and update the element on the page.

We could also check the headers that are returned on the result object to see if application/json is present but it’s not necessarily a guarantee that we have JSON data returned.