193

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();
});
Mark Fisher
  • 965
  • 1
  • 11
  • 30
Sibelius Seraphini
  • 5,303
  • 9
  • 34
  • 55

5 Answers5

313

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
  }
}
Bernat
  • 825
  • 1
  • 6
  • 10
nils
  • 25,734
  • 5
  • 70
  • 79
  • 1
    Via the same strategy you could just use response.json in combination with catch; if you catch an error, it means it's not json. Wouldn't that be a more idiomatic way of handling this (instead of ditching response.json)? – Wouter Ronteltap Nov 10 '18 at 12:23
  • 11
    @WouterRonteltap : Aren't you only allowed to do one or the other. It seems like I remember that you only get one shot at response.anything(). If so, JSON is text, but text isn't necessarily JSON. Therefore, you have to do the sure-thing first, which is .text(). If you do .json() first, and it fails, I don't think you'll get the opportunity to also do .text(). If I'm wrong, please show me different. – Lonnie Best Jan 03 '19 at 09:02
  • 3
    In my opinion you can't trust the headers (even though you should, but sometimes you just can't control the server on the other side). So it's great that you also mention try-catch in your answer. – Jacob Apr 24 '19 at 08:38
  • 3
    Yes, @Lonnie Best is completely correct in this. if you call .json() and it throws an exception (because the response isn't json), you will get a "Body has already been consumed" exception if you subsequently call .text() – Andy Mar 08 '20 at 15:16
  • having problems with random badly formated Json this is THE solution [ clear & short ] – jo_ Jul 21 '21 at 12:38
  • 3
    @Andy you can call response.clone() to get cloned instance and therefore you can call .json() or .text() multiple times. Ref: https://developer.mozilla.org/en-US/docs/Web/API/Response/clone – dKorosec Nov 25 '21 at 09:54
  • 3
    As the https://stevenklambert.com/writing/fetch-json-text-fallback/ article mentions it too, using clone(), u can just: fetch('/file') .then(response => response.clone().json().catch(() => response.text()) ).then(data => { // data is now parsed JSON or raw text }); – onetom May 12 '22 at 10:34
16

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.

larskarbo
  • 380
  • 3
  • 8
  • Very nice! It will still create a 404 error in the browser's console if the URL doesn't exist at all, but I guess it's unavoidable. – LWC Dec 06 '22 at 18:18
0

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;
}
Rakesh Soni
  • 10,135
  • 5
  • 44
  • 51
0

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

aGuegu
  • 1,813
  • 1
  • 21
  • 22
  • [`catch`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch) expects a function type parameter and not the return value of `r.text()` – Peter Seliger Dec 07 '22 at 15:15
  • Thanks @PeterSeliger for pointing out the problem in .catch(r.text()). My eslint has correct mine to .catch(() => r.text()). And I have not looked back and assumed it was working. – aGuegu Dec 08 '22 at 02:07
  • 1
    this was a saver – mr.loop Jul 09 '23 at 17:57
-2

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

Heartbit
  • 1,698
  • 2
  • 14
  • 26