Cómo comprobar si la respuesta de un fetch es un objeto json en javascript


Estoy usando fetch polyfill para recuperar un JSON o texto de una URL, quiero saber cómo puedo comprobar si la respuesta es un objeto JSON o es solo texto

fetch(URL, options).then(response => {
   // how to check if response has a body of type json?
   if (response.isJson()) return response.json();
});
Author: Sibelius Seraphini, 2016-05-09

1 answers

Puede comprobar el content-type de la respuesta, como se muestra en este ejemplo de MDN :

fetch(myRequest).then(response => {
  const contentType = response.headers.get("content-type");
  if (contentType && contentType.indexOf("application/json") !== -1) {
    return response.json().then(data => {
      // process your JSON data further
    });
  } else {
    return response.text().then(text => {
      // this is text, do something with it
    });
  }
});

Si necesita estar absolutamente seguro de que el contenido es JSON válido (y no confiar en los encabezados), siempre puede aceptar la respuesta como text y analizarla usted mismo:

fetch(myRequest)
  .then(response => response.text())
  .then(text => {
    try {
        const data = JSON.parse(text);
        // Do your JSON handling here
    } catch(err) {
       // It is text, do you text handling here
    }
  });

Async / await

Si estás usando async/await, podrías escribirlo de una manera más lineal:

async function myFetch(myRequest) {
  try {
    const reponse = await fetch(myRequest); // Fetch the resource
    const text = await response.text(); // Parse it as text
    const data = JSON.parse(text); // Try to parse it as json
    // Do your JSON handling here
  } catch(err) {
    // This probably means your response is text, do you text handling here
  }
}
 70
Author: nils,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-16 09:05:42