By using Content-Type Header
This approach utilizes the Content-Type header of the response to check if it contains JSON data. If the header includes application/json, the response is parsed as JSON. Otherwise, it will be considered non-JSON.
- We fetch data from the API endpoint using the Fetch API.
- In the then block, we first check if the response status is OK using response.ok. If not, we throw an error.
- We then examine the content-type header of the response to determine if it contains JSON data. If it does, we parse the JSON data using response.json().
- If the response is successfully parsed as JSON, we assign it to the responseData variable and log it to the console.
- If any errors occur during the fetch operation or parsing, we catch and handle them in the catch block.
Example: The below code will explain the use of the Content-Type header to check the response format.
let responseData;
fetch("https://dummyjson.com/products")
.then(response => {
if (!response.ok) {
throw new Error(
'Network response was not ok');
}
const contentType = response.headers.
get('content-type');
if (contentType && contentType.
includes('application/json')) {
return response.json();
} else {
throw new Error(
'Response is not JSON');
}
})
.then(json => {
responseData = json;
console.log(
'Response is a JSON object:',
responseData);
})
.catch(error => {
console.error(
'There was a problem with the fetch operation:',
error);
});
Output:
How to Check if the Response of a Fetch is a JSON Object in JavaScript?
In JavaScript, when making HTTP requests using the Fetch API, it’s common to expect JSON data as a response from the server. However, before working with the response data, it’s essential to verify whether it is indeed a JSON object or not.
The below approaches can help you to check if the response is in JSON format or not:
Table of Content
- By using Content-Type Header
- By Parsing Response Body
Contact Us