Telerik blogs
How ToT2 Dark_1200x303

In this article you will learn what JSON is and how you can deal with errors occurring when parsing JSON data, such as "Unexpected Token < in JSON at Position 0."

What Is JSON

JSON, which is an acronym for JavaScript Object Notation, is one of the most popular data formats used for transmitting data. It is a lightweight format and consists of name-value pairs. Values can be strings, arrays, or any other data that can be serialized.

In the old days XML was primarily used for interchanging data, but since JSON appeared it is often used as a replacement of XML. A JSON file should end with the .json extension.

Below you can see an example of a JSON format.

{
    "name": "animals",
    "animals": [
        "Dog",
        "Cat",
        "Mouse",
        "Pig",
        "Bear"
  ],
  "hobbies": {
        "football": false,
        "reading": true
  }
}

JSON format is quite similar to JavaScript objects, but it is not always the case. It is important to remember that every property name must be wrapped in double quotes.

// not valid JSON
{
  x: 4
}

// valid JSON
{
  "x": 4
}

Unexpected Token < in JSON at Position 0

From time to time when working with JSON data, you might stumble into errors regarding JSON formatting. For instance, if you try to parse a malformed JSON with the JSON.parse() function or use the .json() method on the fetch object, it can result in a JavaScript exception being thrown. But don’t worry, it’s not the end of the world and we can handle it. There can be different causes for this happening so let’s see what we can do about it.

Is My JSON Formatted Correctly?

Projects sometimes require configuration that is sent to the client from a server. Just so you know, storing the config details as a JSON will be faster than using an object literal, as engines need to do more steps when running an object literal than JSON.parse(), for instance. The performance comparison of JSON vs JavaScript is not a topic of this article so it will not be covered, but if you are interested, then you can read more about it here.

If you have a file with JSON data, one of the first things to do is to ensure that the data is formatted correctly. There are a few sites that can help you with that. These formatters not only will check if your JSON is formatted correctly, but they can also fix some of the errors, beautify it, or make it compact.

To be honest, one of the mistakes I am often guilty of myself is using single quotes instead of double quotes. The image below shows how a format checker can make your life easier.

"Invalid JSON (RFC 8259)" is in a red header. Validator output says, "Error: Strings should be wrapped in double quotes." Formatted JSON Data shows some code, and in the line, " 'Name':"Animals," the Name is highlighted in red.

If your JSON is formatted correctly, then it is time to check what else could be wrong.

My JSON is Formatted Correctly—What Next?

“Unexpected token < in JSON at position 0” is the error that I have seen most throughout my time of working as a software developer. Quite often it happens in a situation when fetch function is used for sending an API request from a client. After receiving a response from a server, usually it is parsed to JSON.

fetch(‘url’).then(response => response.json())

The first thing to do in this situation is to confirm where the error is happening exactly. To ensure the error happens on the exact line we think it does, we can wrap the JSON parsing code in a try-catch block. Check the code below.

fetch("url").then(async response => {
      try {
       const data = await response.json()
       console.log('response data?', data)
     } catch(error) {
       console.log('Error happened here!')
       console.error(error)
     }
    })

If this is the culprit, then it will be clearly visible in the developer tools console, as “Error happened here!” will be displayed. Otherwise, you might need to look for it somewhere else. A good idea is to sometimes comment out code piece by piece to see when an error stops being thrown. You can also use an early return statement.

The next step is to check if the data we are expecting to see is actually being sent from the server. As shown on the image below, head to the “Network” tab in DevTools, find the request, and click on the “Response” tab.

In the "Network" tab of a code window, under the "Response" tab, we're examining some code.

In this example, we can see a JSON string sent from the swapi API, so it is correct. However, in a different case, the response could be in the XML format or the server could have sent an HTML file. The former could happen if you are dealing with a server that can return different responses depending on the content-type header provided. If this is the case, when you send a request, make sure you specify the content-type header as shown below:

fetch(‘url’, {
  method: ‘GET’,
  headers: {
    ‘Content-Type’: ‘application/json’
  }
}).then(response => response.json())

As for the latter, I have seen the server sending an HTML file on a few occasions. Usually, a reason for this was an incorrect URL provided to the fetch method, or the API server route was not set up correctly. For example, if you have a Single Page Application and a backend running Express.js server, it could be set up to always serve an index.html file. Therefore, always double-check your URLs and API routes configuration.

Conclusion

JSON is an extremely popular format and is commonly used for data interchanging. We have talked about what JSON is, and what we can do when a parsing error is thrown. For starters, always double-check if the values you are dealing with are what you expect them to be, and remember, console.log() is your friend.


Thomas Findlay-2
About the Author

Thomas Findlay

Thomas Findlay is a 5-star rated mentor, full-stack developer, consultant, technical writer and the author of “React - The Road To Enterprise” and “Vue - The Road To Enterprise.” He works with many different technologies such as JavaScript, Vue, React, React Native, Node.js, Python, PHP and more. Thomas has worked with developers and teams from beginner to advanced and helped them build and scale their applications and products. Check out his Codementor page, and you can also find him on Twitter.

Comments

Comments are disabled in preview mode.