By Parsing Response Body

In this approach, we will attempt to parse the response body directly in JSON using theresponse.json() method. The errors will be handled using the catch callback to identify non-JSON responses.

Example: The below code will explain how you can parse fetched response to JSON.

JavaScript
fetch("https://dummyjson.com/products")
    .then(response => {
        if (!response.ok) {
            throw new Error(
                'Network response was not ok');
        }
        return response.json();
    })
    .then(json => {
        console.log(
            'Response is a JSON object:', 
            json);
    })
    .catch(error => {
        console.error('Error:', 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

Similar Reads

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....

By Parsing Response Body

In this approach, we will attempt to parse the response body directly in JSON using theresponse.json() method. The errors will be handled using the catch callback to identify non-JSON responses....

Contact Us