try/catch判断
function isJSON(str) {
if (typeof str == 'string') {
try {
JSON.parse(str);
return true;
} catch(e) {
console.log(e);
return false;
}
}
console.log('It is not a string!')
}
以上try/catch
的确实不能完全检验一个字符串是JSON
格式的字符串,有许多例外:
JSON.parse('123'); // 123
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
增强
那我们再判断下JSON.parse(str)的类型就好了
if (value === '{}') {
return true
} else {
try {
if (Object.prototype.toString.call(JSON.parse(value)) === '[object Object]') {
return true
} else {
return false
}
} catch (e) {
return false
}
}