js 判断字符串是否为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!')
}

var obj = JSON.parse(str)

typeof obj == 'object' && obj

用try catch盖住报错。

posted @ 2019-12-09 13:57  Redchar  阅读(6859)  评论(0编辑  收藏  举报