How to check if the response of a fetch is a json object in javascript

前端 未结 3 1177
Happy的楠姐
Happy的楠姐 2020-12-13 05:28

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(UR         


        
相关标签:
3条回答
  • 2020-12-13 05:57

    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.

    0 讨论(0)
  • 2020-12-13 06:01

    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 => {
          // process your JSON data further
        });
      } else {
        return response.text().then(text => {
          // this is text, do something with it
        });
      }
    });
    

    If you need to be absolutely sure that the content is 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())
      .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

    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); // 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
      }
    }
    
    0 讨论(0)
  • 2020-12-13 06:10

    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;
    }
    
    0 讨论(0)
提交回复
热议问题