Sibelius Seraphini
Sibelius Seraphini

Reputation: 5633

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();
});

Upvotes: 223

Views: 188781

Answers (7)

1.21 gigawatts
1.21 gigawatts

Reputation: 17816

Here's an await and async answer based on @nils answer checking the content type first before calling response.json(). No cloning needed.

async function myFetch(myRequest) {
  try {
    const response = await fetch(myRequest);
    const contentType = response.headers.get("content-type");
    var data;
    if (contentType && contentType.includes("application/json")) {
       data = await response.json(); 
    }
    else {
       data= await response.text();
    }

    return data;
  }
  catch(error) {
    // other errors occurred
    throw error;
  }
}

try {
   var json = await myFetch("test");
   if (json && json.success) { 
      // do something
   }
}
catch(error) {

}

Another example that throws an error if it's not json (not tested):

async function myFetch(myRequest, noJsonFunction) {
  try {
    const response = await fetch(myRequest);
    const contentType = response.headers.get("content-type");
    var data;
    if (contentType && contentType.includes("application/json")) {
       data = await response.json();
       return data;
    }
    throw new Error(response);
  }
  catch(error) {
    throw error;
  }
}

// use
try {
   var json = await myFetch("test");
}
catch(error|response) {
   if (error instanceof Error) {}
   if (error instanceof Response) {}
}

Upvotes: 2

hossein sedighian
hossein sedighian

Reputation: 2055

i decided to use this one

   return fetch(url).then(async k =>{
             const res = await k.text();
             if(res.startsWith("[") || res.startsWith("{")){
                return JSON.parse(res);
             }
             console.warn(url + " Did not pass Json Format");   
             return [];
            }).then(g => {          
          ////
        }) 
       

Upvotes: -1

aGuegu
aGuegu

Reputation: 2299

Fetch returns a Promise. with Promise chain, a one liner like this would work.

const res = await fetch(url, opts).then(r => r.clone().json().catch(() => r.text()));

enter image description here

Upvotes: 0

nils
nils

Reputation: 27204

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

Upvotes: 358

Heartbit
Heartbit

Reputation: 1836

I recently published an npm package that includes common utility functions. one of these functions that I implemented there is just like the nis's async/await answer that you can use as bellow:

import {fetchJsonRes, combineURLs} from "onstage-js-utilities";

fetch(combineURLs(HOST, "users"))
    .then(fetchJsonRes)
    .then(json => {
        // json data
    })
    .catch(err => {
        // when the data is not json
    })

you can find the source on Github

Upvotes: -1

larskarbo
larskarbo

Reputation: 460

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.

Upvotes: 21

Rakesh Soni
Rakesh Soni

Reputation: 10887

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;
}

Upvotes: -1

Related Questions