Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the response of a fetch is a json object in javascript

I'm using fetch polyfill to retrieve a JSON or text from a URL, I want to know how can I check if the response is a JSON object or is it only text

fetch(URL, options).then(response => {
   // how to check if response has a body of type json?
   if (response.isJson()) return response.json();
});
like image 229
Sibelius Seraphini Avatar asked May 09 '16 16:05

Sibelius Seraphini


People also ask

How do I get JSON from fetch response?

To get JSON from the server using the Fetch API, you can use the response. json() method. The response. json() method reads the data returned by the server and returns a promise that resolves with a JSON object.

How do you know if a response is XML or JSON?

Check the content type of the response message. You can also read the first character from the response. If it's a XML content, you should find a < . Even if the XML declaration is present or not.

What does Response JSON () do in Fetch?

json() The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON .


3 Answers

You could check for the content-type of the response, as shown in this MDN example:

fetch(myRequest).then(response => {
  const contentType = response.headers.get("content-type");
  if (contentType && contentType.indexOf("application/json") !== -1) {
    return response.json().then(data => {
      // The response was a JSON object
      // Process your data as a JavaScript object
    });
  } else {
    return response.text().then(text => {
      // The response wasn't a JSON object
      // Process your text as a String
    });
  }
});

If you need to be absolutely sure that the content is a valid JSON (and don't trust the headers), you could always just accept the response as text and parse it yourself:

fetch(myRequest)
  .then(response => response.text()) // Parse the response as text
  .then(text => {
    try {
      const data = JSON.parse(text); // Try to parse the response as JSON
      // The response was a JSON object
      // Do your JSON handling here
    } catch(err) {
      // The response wasn't a JSON object
      // Do your text handling here
    }
  });

Async/await

If you're using async/await, you could write it in a more linear fashion:

async function myFetch(myRequest) {
  try {
    const reponse = await fetch(myRequest);
    const text = await response.text(); // Parse it as text
    const data = JSON.parse(text); // Try to parse it as JSON
    // The response was a JSON object
    // Do your JSON handling here
  } catch(err) {
    // The response wasn't a JSON object
    // Do your text handling here
  }
}
like image 177
nils Avatar answered Oct 18 '22 22:10

nils


You can do this cleanly with a helper function:

const parseJson = async response => {
  const text = await response.text()
  try{
    const json = JSON.parse(text)
    return json
  } catch(err) {
    throw new Error("Did not receive JSON, instead received: " + text)
  }
}

And then use it like this:

fetch(URL, options)
.then(parseJson)
.then(result => {
    console.log("My json: ", result)
})

This will throw an error so you can catch it if you want.

like image 13
larskarbo Avatar answered Oct 18 '22 22:10

larskarbo


Use a JSON parser like JSON.parse:

function IsJsonString(str) {
    try {
        var obj = JSON.parse(str);

         // More strict checking     
         // if (obj && typeof obj === "object") {
         //    return true;
         // }

    } catch (e) {
        return false;
    }
    return true;
}
like image 3
Rakesh Soni Avatar answered Oct 18 '22 20:10

Rakesh Soni