Подтвердить что ты не робот

Как проверить, является ли ответ на выборку json-объектом в javascript

Я использую fetch polyfill для извлечения JSON или текста из URL-адреса, я хочу знать, как проверить, является ли ответ объектом JSON, или это только текст

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

Ответ 1

Вы можете проверить content-type ответа, как показано в этом примере 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
    });
  }
});

Если вам нужно быть абсолютно уверенным, что содержимое является допустимым JSON (и не доверяете заголовкам), вы всегда можете просто принять ответ как text и проанализировать его самостоятельно:

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

Асинхронный /Await

Если вы используете async/await, вы можете написать его более линейно:

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

Ответ 2

Используйте анализатор JSON, например 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;
}