Error syntaxerror unexpected token in json at position 0

Getting SyntaxError: Unexpected token < in JSON at position 0 when using fetch or JSON.parse. I will go over fixes for this!

Introduction

A common issue that I see when working with front-end JavaScript heavy apps is the dreaded “SyntaxError Unexpected Token in JSON” error! Now this error can be of the form:

SyntaxError: Unexpected token < in JSON at position 0

SyntaxError: Unexpected end of JSON input

syntaxerror: unexpected token '<', "<!doctype "... is not valid json

The error “SyntaxError Unexpected Token in JSON” appears when you try to parse content (for example — data from a database, api, etc), but the content itself is not JSON (could be XML, HTML, CSV) or invalid JSON containing unescaped characters, missing commas and brackets.

There are a few things you can try to fix this error:

  1. Check that the content you are trying to parse is JSON format and not HTML or XML

  2. Verify that there are no missing or extra commas.

  3. Make sure to check for unescaped special characters.

  4. Check for mismatched brackets or quotes.

  5. Make sure the JSON is valid. You can use a tool like JSONLint to validate your JSON and check for any errors.

1. Check that the content you are trying to parse is JSON format and not HTML or XML

A common reason why the error “SyntaxError Unexpected Token in JSON” comes up is that we are trying to parse content that is not even JSON.

Consider the following front-end JavaScript code:

  

fetch('https://localhost:3000/data')
  .then(response => response.json())
  .then(data => {
    console.log(data);
    // Use the data here
  })

In the above example, the fetch() function is being used to retrieve data from a API that returns JSON format — in this case https://localhost:3000/data.

The fetch() function then returns a promise, and when that promise resolves, we handle that with the response.json() method. This just takes our JSON response and converts it to a JSON object to be used!

After that we just console.log out the data object

Now for the server-side of things, look on to our Node JS route that returns the JSON /data

  

var http = require('http');

var app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'text/html');  Not returning JSON.
    res.end(JSON.stringify({ a: 1 }));
});
app.listen(3000);

We can see that it is setting the Header as text/html. This will give you the error:

syntaxerror: unexpected token '<', "<!doctype "... is not valid json

This is because we are trying to parse the content with JSON.parse() or in our case response.json() and receiving a HTML file!

To fix this, we just need to change the returned header to res.setHeader('Content-Type', 'application/json'):

  

...
var app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'application/json'); ✔️ Returning JSON.
    res.end(JSON.stringify({ a: 1 }));
});
...

Whats Content-Type request header anyway?

Pretty much every resource on the internet will need to have a type (similar to how your file system contains file types like images, videos, text, etc).
This is known as a MIME type (Multipurpose Internet Mail Extension)

Browsers need to know what content type a resource is so that it can best handle it. Most modern browsers are becoming good at figuring out which content type a resource is, but its not always 100% correct.

That is why still need to explicitly specify our request header content-type!

syntaxerror: unexpected token ‘<’, “<!doctype “… is not valid json

This error also comes up when your API is returning invalid error pages such as 404/500 HTML pages. Since HTML usually starts with a “less than” tag symbol (<) and JSON is not valid with < tags, it will through this error.

For example, when everything is working find, your node API will happily return JSON. However when it fails with a 500 internal error, it could return a custom HTML error page!
In this case, when you try to do JSON.parse(data) you will get the syntaxerror: unexpected token '<', "<!doctype "... is not valid json.

Additionally, check that you are calling the correct API url. As an example, lets say the API that returns JSON is using the /data route. If you misspelt this, you could be redirected to a 404 HTML page instead!

Tip: Use appropriate error handlers for non-JSON data

If you are using fetch() to retrieve your data, we can add a catch handler to give meaningful error messages to the user:

  

fetch('https://localhost:3000/data')
  .then(response => response.json())
  .then(data => {
    console.log(data);
    // Use the data here
  })
  .catch(error => console.error(error)); /*✔️ Friendly error message for debugging! */

If you are using JSON.parse() we can do this in a try/catch block as follows:

  

try {
    JSON.parse(data);
}
catch (error) {
    console.log('Error parsing JSON:', error, data); /*✔️ Friendly message for debugging ! */
}

JSON objects and arrays should have a comma between each item, except for the last one.

  

{
    "name": "John Smith"
    "age": 30
    "address": {
        "street": "123 Main St"
        "city": "Anytown"
        "state": "USA"
    }
}

This JSON object will throw a “syntaxerror unexpected token” error because there is no comma between “John Smith” and “age”, and also between “Anytown” and “state”.

To fix this, you would add commas as follows:

  

{
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "USA"
    }
}

By adding commas between each item except for the last one, the JSON object is now in the correct format and should parse without error.

3. Make sure to use double quotes and escape special characters.

JSON strings must be wrapped in double quotes, and any special characters within the string must be properly escaped. Consider the following example:

  

{
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "USA"
    },
    "message": "It's a lovely day"
}

When we try to parse this with JSON.parse, we will get the error: SyntaxError: Invalid or unexpected token.

The problem is with the following line using a apostrophe:

"message": "It's a lovely day"

  

{
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "USA"
    },
    "message": "It's a lovely day"
}

As we can see, this will fix our error since we escape the aspostrophe as such:

"message": "It's a lovely day"

4. Check for mismatched brackets or quotes.

Make sure all brackets and quotes are properly closed and match up.

  

{
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "USA"
    }

In this example, the JSON object is missing a closing curly bracket, which indicates the end of the object. Because of this, it will throw a “syntaxerror unexpected token” error.

To fix this, you would add the missing closing curly bracket as follows:

  

{
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "USA"
    }
}

If you want to be sure that the JSON is valid, we can try to use the NPM package JSONLint (https://github.com/zaach/jsonlint)

We can install jsonlint with npm as follows:

  1. Open up the terminal
  2. Run NPM install npm install jsonlint -g
  3. We can then validate a file like so: jsonlint myfile.json

Summary

In this article I went over the SyntaxError: Unexpected token < in JSON at position 0 when dealing with parsing JSON with fetch or JSON.parse. This error is mainly due to the JSON not being in correct format or the content that we are trying to parse is not even JSON.

In the case of JSON being invalid, make sure to check for unescaped characters, missing commas, non-matching brackets and quotes.

To be really sure, check the JSON with tools like JSONLint to validate!

In the case of the content you are trying to parse being non-JSON such as HTML, check your API to make sure that error pages return JSON correctly instead of HTML pages.

Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0

You made an HTTP request, probably with Fetch, and it blew up with this error. Or a very similar one.

Ugh.

Here’s what causes it and how to fix it.

Read on for a quick suggestion, and watch the video for a walkthrough of a few techniques you can try to debug this in your own app.

How to fix Unexpected Token in JSON error

The Cause

This happens when you make a request to the server and parse the response as JSON, but it’s not JSON. The code responsible might look something like this:

fetch('/users').then(res => res.json())

The actual request worked fine. It got a response. But the res.json() is what failed.

JSON.parse

You might instead be parsing the JSON yourself with JSON.parse like this:

JSON.parse(theStringThatIsNotJson);

JSON.parse is what fetch’s res.json() is doing under the hood, so the error will be the same either way.

Valid JSON

JSON should start with a valid JSON value – an object, array, string, number, or false/true/null. This response started with a < (hence the “Unexpected token <”).

That unexpected token, <, is a strong clue that the response was HTML instead of JSON.

The root cause is that the server returned HTML or some other non-JSON string. Why would it do that?

“Unexpected token o in JSON at position 1” and other varieties

The exact text of this error will differ depending on what the server returned. The token and the position may vary, but the root cause is the same: the text that your app is trying to parse as JSON is not actually valid JSON.

Here are some other variations I’ve seen…

  • Unexpected token < in JSON at position 1
  • Unexpected token p in JSON at position 0
  • Unexpected token d in JSON at position 0

Watch the video above for how this error works, and how to use your browser’s developer tools to figure out exactly what’s causing it. (or keep on readin’)

The Fix

The first thing to do is try logging it out. With fetch, you can use res.text() instead of res.json() to get the text string itself. Alter your code to read something like this, and check the console to see what’s causing the problem:

fetch('/users')
  // .then(res => res.json()) // comment this out for now
  .then(res => res.text())          // convert to plain text
  .then(text => console.log(text))  // then log it out

Note that these res.json() and res.text() functions are asynchronous, so you cannot log their return value directly. That’s why the console.log must be in a separate .then block.

Fix JSON.parse Unexpected Token

If you’re using JSON.parse directly, that’s a plain old synchronous call and you can replace the call with a console.log to see what’s going on.

// JSON.parse(someString)  // comment this out temporarily
console.log(someString)    // log out out, and see what's wrong

Blame the Server?

The server might return HTML instead of JSON for a bunch of reasons:

  • The URL doesn’t exist and the server returned an 404 page as HTML. You might have a typo in the client code (/users instead of /user) or in the server code that sets up the route.
  • The server might need a restart if you just added a URL to it. If you’re using an Express server for instance, and you just added a new app.get('/users', ...) route, but didn’t restart the server, then it doesn’t know about the new route yet.
  • The client’s proxy isn’t set up: if you’re using a Webpack dev server like Create React App, you can set up a proxy to forward requests to a backend server.
  • The API root URL is /: If you’re using a proxy through Webpack or Create React App, make sure your API route is not at the root level /. That’ll confuse the proxy and you’ll get back HTML instead of your API request. Instead, prefix the route with something like /api/.

Also, check the browser devtools Network tab and look for the request that caused this error, and then look at the response that came back.

Is it a 404 page? (might be a missing route or a typo)

Is it the index.html page? (might be a missing route or a misconfigured proxy)

If everything looks fine, then restart your backend server and your frontend dev server, and see if the problem goes away.

Problem Solved?

Hopefully you’ve now gotten rid of the error. If not, leave a comment below with what you tried.

Learning React can be a struggle — so many libraries and tools!
My advice? Ignore all of them :)
For a step-by-step approach, check out my Pure React workshop.

Pure React plant

Learn to think in React

  • 90+ screencast lessons
  • Full transcripts and closed captions
  • All the code from the lessons
  • Developer interviews

Start learning Pure React now

Dave Ceddia’s Pure React is a work of enormous clarity and depth. Hats off. I’m a React trainer in London and would thoroughly recommend this to all front end devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavender

@lavenderlens

Table of Contents

If you are coding in JavaScript, React, or any other JavaScript library/framework, you would have come across the following errors:

SyntaxError: Unexpected token < in JSON at position 0

SyntaxError: Unexpected end of JSON input

When does this error occur?

This error occurs when you are trying to parse a string to JSON and the string is not parsable.
In other words, it happens when you pass an invalid JSON string to JSON.parse() function.

Try executing the following code in the browser console:

You will see the following error:

json parse error 1

So the error is telling that it is seeing a string < at the beginning since a valid JSON should start with {.

Now if you execute the following code, you will get the second error:

json parse error 2

If you observe the JSON string, it starts as a valid JSON, however, the JSON is not complete. Hence it is telling ‘unexpected end of JSON input’.

Let’s now see how we can reproduce same issue in React application:

App.js

1import { useEffect } from "react"

2

3function App() {

4 useEffect(() => {

5 const fetchData = async () => {

6 const response = await fetch("https://jsonplaceholder.typicode.com/")

7 const data = await response.json()

8 console.log({ data })

9 }

10

11 fetchData()

12 }, [])

13 return <div className="App">home</div>

14}

15

16export default App

The above code attempts to fetch the data from https://jsonplaceholder.typicode.com/ and calls response.json().
When we call response.json(), it internally calls JSON.parse() to convert the response into a JSON Object.

However, the URL we have passed is of an HTML page and we will be getting an HTML string as the response.
Hence, if you execute the above code, it will throw the error: SyntaxError: Unexpected token < in JSON at position 0.

How to fix this issue?

We can fix this issue by making sure that we are calling the right endpoint and we are getting a valid JSON response.

We can do so by opening the URL in the browser and checking the content-type response header:

HTML content type

html content type

JSON content type

If you check the content-type of an endpoint that returns a valid JSON, like https://jsonplaceholder.typicode.com/posts,
you will see the content-type as application/json.

json content type

You could also validate if a string is a valid JSON or not in tools like JSON Formatter.

If you have liked article, stay in touch with me by following me on twitter.

Author: Chukwuka Reuben

Introduction.

This post aims to address the «Unexpected token in JSON at position 0» error message. We will look into the various possible causes of this message and suggest methods to rectify it.

Steps we’ll cover:

  • What is JSON?
  • What does the «Unexpected token < in JSON at position 0» error mean?
  • Different Reasons Why You Might Have This Error and Their Fixes.
  • Hitting Any API endpoint that does not exist:
  • Spelling Error
  • Forgetting to stringify your object:

What is JSON?

JSON which stands for Javascript Object Notation can be said to be a lightweight format for storing and transporting data, it is used often when data is sent from a server to a webpage.

If you have ever utilized API endpoints in your projects before, there’s a very high chance that JSON is being used to store and transport data between your web page and servers.

Let us quickly examine the utilization of JSON for transporting and storing data. We don’t need to look too far since the local storage on our internet browsers can function as servers.

The codeblock below shows how JSON can be used to transport data between local storage and the web page:

localStorage.setItem('list', JSON.stringfy(list))

JSON.parse(localStorage.getItem('list'))

Enter fullscreen mode

Exit fullscreen mode

Now that we are aware of what JSON is and how it can be applied, let us move on to resolving the «Unexpected token in JSON at position 0» error message.

What does the «Unexpected token < in JSON at position 0» error mean?

In very simple language, «Unexpected token < in JSON at position 0» indicates that you are parsing something else that is not JSON as JSON.

To prove my point, I will attempt to reproduce the mistake. Go to your browser console and execute this code snippet:

JSON.parse(undefined)

Enter fullscreen mode

Exit fullscreen mode

The code snippet above will produce this type of error:

json error description

Why? because «undefined» is not JSON but we have tried to parse it as JSON.

There’s something I would like you to note before we proceed:

The actual «Unexpected token in JSON at position 0» message may vary depending on what your server generates, however, the fundamental reason remains the same: you are attempting to parse something that is not JSON as JSON.

Below are some of the different forms in which the error message could be presented:

  • » is not a valid JSON at JSON.parse».

  • Unexpected token ‘<‘, «<!DOCTYPE «… is not valid JSON.

  • Unexpected token ‘o’, «not found!» is not valid JSON.

  • Unexpected token ‘o’, «[object obj… is not valid JSON»

and so on. So going forward I’ll be using the general name «JSON.parse unexpected token» to refer to this error.

Now that we know what the «JSON.parse unexpected token» error means, let us proceed to know the different reasons why you might have this error and also look into ways to fix them.

Different Reasons Why You Might Have This Error and Their Fixes.

In this section of this article, 4 reasons and their fixes will be listed:

Hitting Any API endpoint that does not exist:

This is one of the most common causes of this error, and this tends to occur during the fetch request in javascript.

As you might have already assumed, yes! it occurs when you’re trying to parse an endpoint result that is not JSON as JSON.

In this part of the article, we will consider two brief cases — one to obtain a valid endpoint and show the outcome, and the other to retrieve an endpoint that doesn’t exist so we can reproduce the error message.

Example 1:

In this example, I’ve used the JSON endpoints from https://dummyjson.com/, a place where you can get fake JSON data to use during development.

I’ve picked a valid endpoint from this site and went ahead to call the javascript fetch method on it, check out the code snippet and its result below:

fetch('https://dummyjson.com/products/1')
  .then(res => res.json())
  .then(json => console.log(json))

Enter fullscreen mode

Exit fullscreen mode

Using the code snippet above, I want to clarify that JSON.parse() is being done by res.json() under the hood.

error description

The image above shows that we got a valid JSON response, now let us move to the second example.

Example 2:

fetch("https://dummyjson.com/myProduct/1")
    .then((res) => res.json())
    .then((json) => console.log(json));

Enter fullscreen mode

Exit fullscreen mode

https://dummyjson.com/myProduct/1 that has been used as our API is an endpoint that I made up, so it is not a valid API endpoint and as you know parsing it will be you trying to parse something that isn’t JSON, as it is not a formatted JSON.

error description

How To Fix.

  • Make sure you are using a valid API endpoint:

    To make sure you are using a valid JSON endpoint, use JSONFORMATTER to verify your endpoints before using it.

  • Always use the try-and-catch within your fetch method or function to prevent your app from crashing.

Spelling Error

This is so much similar to hitting the wrong API, only that you might have been pretty sure that the API endpoint exists.

Spelling error tends to happen due to typographical error or maybe you don’t know what the correct spellings are.

Spelling errors do not apply only to API endpoints, they can also occur while attempting to fetch information from your local storage and lead to the «JSON.parse unexpected token» error message showing up.

How To Fix.

  • Check and proofread well before hitting the API.

  • Make sure you verify your API before hitting it. use JSONFORMATTER.

  • Use the try-and-catch method in your function to prevent your app from crashing.


Building a side project?

Meet the headless, React-based solution to build sleek CRUD applications. With refine, you can build complex projects without having advanced frontend skills.

Try refine to rapidly build your next CRUD project, whether it’s an admin panel, dashboard, internal tool or storefront.

refine blog logo


Forgetting to stringify your object:

If we don’t use the JSON.stringify() technique to convert our object into a string before sending it to a server, then we may encounter the error «JSON.parse unexpected token». This raises the question, «why is it necessary to transform our object into a string before sending it to a server?»

When sending data to a web server, the data has to be a string and to convert a javascript object to a string JSON.stringify() does the trick.

We are going to take two quick examples in this section, example 1 will represent the problem and example 2 will be the solution.

Example 1

Note:

Local storage will stand as our servers in this example.

I have a list of todos that I have written on my web page, I wish for them to stay even after I have reloaded my page*,* how do I make that happen?

I have to send those lists as data to my server, and then to retrieve them whenever I reload the page.

localStorage.setItem("list", 
list);

Enter fullscreen mode

Exit fullscreen mode

In the code snippet that I have provided, I have sent my data to the server without converting the object to a string using JSON.stringify(). Let’s take a look at the consequence this will have on our page, below is the code snippet for retrieving the list, and an image of the result:

const getLocalStorage = () => {
  let list = localStorage.getItem("list");
  if (list) {
    return (list = JSON.parse(localStorage.getItem("list")));
  } else {
    return [];
  }
};

Enter fullscreen mode

Exit fullscreen mode

error description

The error indicates that I’m trying to parse an object, and it’s not a valid JSON.

Example 2(The fix):

All we have to do to fix this error is to stringify our list before sending it to the server:

localStorage.setItem("list", 
JSON.stringify(list))

Enter fullscreen mode

Exit fullscreen mode

The code snippet above will fix the error.

In general, it is always a good idea to carefully check your JSON data for any syntax errors before attempting to parse it. This will help to ensure that your code is able to properly handle the JSON data and avoid any errors like the «Unexpected token in JSON at position 0» error.

This guide will help you to fix SyntaxError: Unexpected token < in JSON at position 0. This guide also applies to these other common variants of the same error:

  • SyntaxError: The string did not match the expected pattern.

  • SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

  • JSON parse error: Unrecognised token '<'

Summary

These errors indicate that your JavaScript code expected to receive JSON but got something else instead (probably HTML in the form of a server-side error). To fix the issue, you need to examine what you got instead of the expected JSON to determine what the problem is.

Details

Usually, this error is caused when your server returns HTML (which typically begins with <DOCTYPE html> or <html>) instead of JSON. Valid JSON cannot begin with a < character, so the JSON parser knows immediately that the data isn’t valid JSON and produces one of the error messages mentioned above.

To fix this error, you need to figure out why you’re getting HTML (or something else) instead of the JSON you expected. To do this, you need to log the data that you’re trying to parse to the console.

If you’re using fetch()

Use this approach if your code looks something like this:

fetch('https://example.com/some/path/to/json')
.then(function (response) {
    return response.json();
})
.then(function (data) {
    // Do something with data
});

In this case, the error is thrown when response.json() tries to run and fails to parse the data from the server as JSON. You can add a function to handle the error, display the raw text of the response body from the server and log it to the console (see notes about commented lines below):

var responseClone; // 1
fetch('https://example.com/some/path/to/json')
.then(function (response) {
    responseClone = response.clone(); // 2
    return response.json();
})
.then(function (data) {
    // Do something with data
}, function (rejectionReason) { // 3
    console.log('Error parsing JSON from response:', rejectionReason, responseClone); // 4
    responseClone.text() // 5
    .then(function (bodyText) {
        console.log('Received the following instead of valid JSON:', bodyText); // 6
    });
});

Here’s an explanation of each line with a numbered comment:

  1. responseClone variable is required to hold a clone of the response object because the body of a response can only be read once. When response.json() is called, the body of the original response is read, which means it cannot be read again while handling the JSON parse error. Cloning the response to responseClone provides two copies of the response body to work with; one in the original response to use with response.json() and another to use with responseClone.text() if response.json() fails.

  2. This line populates the responseClone variable with a clone of the response received from the server.

  3. A second function argument is passed to the then() function that follows the response.json() call. This second function will be called if the promise from response.json() is rejected (i.e. a JSON error is encountered).

  4. This line logs the rejectionReason from the rejected response.json() promise and the responseClone so it can be examined if needed (the HTTP status code is often useful for debugging, for example).

  5. Instead of trying to parse the response body from the server as JSON, it is processed as raw text.

  6. The body text is logged to the console for examination.

If you’re using JSON.parse()

Use this method if the code that’s throwing the error looks like this:

JSON.parse(data);

In this case, you can log the data to the console if an error is encountered to see what it contains:

try {
    JSON.parse(data);
}
catch (error) {
    console.log('Error parsing JSON:', error, data);
}

What do I do next?

Once you can see the data that’s causing the JSON parse error, it will hopefully provide a clue as to why you’re not getting the valid JSON you expect. Some of the most common issues that lead to this error are:

  • If you see HTML indicating a 404 Not Found error instead of the JSON you expect, check the URL you’re passing to fetch() and make sure that it’s correct.

  • If you see HTML indicating a server error (such as a 500 error code), examine your server’s error logs to determine why your server is encountering an error instead of providing the JSON you expect.

  • If you cannot see anything or if you have an unusual jumble of characters, check your variable assignments and character encodings.

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.

  • https://jsonformatter.org/
  • https://jsonformatter.curiousconcept.com/
  • https://codebeautify.org/jsonvalidator

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.

Понравилась статья? Поделить с друзьями:
  • Error syntax error xerox
  • Error syntax error while loading yaml found unexpected end of stream
  • Error syntax error while loading yaml did not find expected indicator
  • Error syntax error while loading yaml could not find expected
  • Error syntax error while loading yaml ansible