Categories
JavaScript Answers

How to Check if the Response of a Fetch is a JSON Object in JavaScript?

Spread the love

We can check if a response of a fetch call is a JSON object with JavaScript by putting the fetch call in a try-catch block and use JSON.parse to parse the response string.

For instance, we can write:

const myFetch = async (myRequest) => {  
  try {  
    const response = await fetch(myRequest);  
    const text = await response.text();  
    const data = JSON.parse(text);  
    console.log(data)  
  } catch (err) {  
    console.log(err)  
  }  
}  
myFetch('https://yesno.wtf/api')

to create the myFetch function with the myRequest string parameter for the URL.

We pass myRequest into fetch to make the request

Then we call response.text to get the response string.

Next, we call JSON.parse with text to try to parse the response string.

If it’s successful, data should be assigned the parsed JSON object.

Otherwise, an error will be raised and err is logged.

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 *