Uncaught SyntaxError: Unexpected token a in JSON at position 0
at JSON.parse (<anonymous>)
下面这个函数可以判断字符串是否为JSON格式,如果是,则返回true。如果不是,也不会报错,而是用try catch盖住报错,抛出异常,并返回false:
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
