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.