Categories
JavaScript Answers

How to check if the response of a fetch is a JSON object in JavaScript?

Spread the love

Sometimes, we want to check if the response of a fetch is a JSON object in JavaScript.

In this article, we’ll look at how to check if the response of a fetch is a JSON object in JavaScript.

How to check if the response of a fetch is a JSON object in JavaScript?

To check if the response of a fetch is a JSON object in JavaScript, we can check the content-type response header.

For instance, we write

const response = await fetch(myRequest);
const contentType = response.headers.get("content-type");
if (contentType?.indexOf("application/json") !== -1) {
  //...
} else {
  //...
}

in an async function to call fetch to make a request.

Then we get the content-type header with response.headers.get("content-type").

And then we check if its value includes 'application/json'.

If it does, then the response should be JSON.

Conclusion

To check if the response of a fetch is a JSON object in JavaScript, we can check the content-type response header.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *