js判断字符串是否为正确的JSON格式及JSON格式化的实现

判断是否是正确的JSON格式

function isJSON(str) {
    if (typeof str == 'string') {
        try {
            var obj=JSON.parse(str);
            if(typeof obj == 'object' && obj ){
                return true;
            }else{
                return false;
            }

        } catch(e) {
            console.log('error:'+str+'!!!'+e);
            return false;
        }
    }
    console.log('It is not a string!')
}

JSON格式化(先判断是不是正确的JSON格式)

 function formatRequest(str){
       if(isJSON(str)){
           var JSONString = JSON.stringify(JSON.parse(str), null, "	");
       }else{
           alert("不是正确的JSON格式")
       }
}

参考:https://www.cnblogs.com/lanleiming/p/7096973.html

原文地址:https://www.cnblogs.com/zhoushuang0426/p/11188513.html