web-dev-qa-db-fra.com

Comment vérifier si la réponse d'une extraction est un objet json en javascript

J'utilise fetch polyfill pour récupérer un texte JSON ou une URL, je souhaite savoir comment vérifier si la réponse est un objet JSON ou s'il s'agit uniquement de texte 

fetch(URL, options).then(response => {
   // how to check if response has a body of type json?
   if (response.isJson()) return response.json();
});
46

Vous pouvez vérifier le content-type de la réponse, comme indiqué dans cet exemple 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 vous devez être absolument sûr que le contenu est un fichier JSON valide (et ne faites pas confiance aux en-têtes), vous pouvez toujours accepter la réponse sous la forme text et l'analyser vous-même:

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/wait

Si vous utilisez async/await, vous pouvez l'écrire de manière plus linéaire:

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

Utilisez un analyseur JSON tel que 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;
}
0
Rakesh Soni