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

前端 未结 3 1176
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 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;
    }
    

提交回复
热议问题