【最简单的方法】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) {
·
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!')
}
我们知道,JS中的数据类型分为:字符串、数字、布尔、数组、对象、Null、Undefined。
那我们就针对这几种类型的字符串进行测试。
function isJSON_test(str) {
if (typeof str == 'string') {
try {
var obj=JSON.parse(str);
console.log('转换成功:'+obj);
return true;
} catch(e) {
console.log('error:'+str+'!!!'+e);
return false;
}
}
console.log('It is not a string!')
}
isJSON_test('123'); //number
isJSON_test('aaaa'); //string
isJSON_test('"aaa"');
isJSON_test('true'); //布尔
isJSON_test('["1","2"]'); //数组
isJSON_test('{name:"123"}'); //对象
isJSON_test('{}'); //空对象
isJSON_test('null'); //null
isJSON_test('Undefined'); //Undefined
isJSON_test('{"name":"123"}'); //json
isJSON_test('{"name":"123",}'); //不规范的json
isJSON_test('["1{211323}","2"]'); //数组 :含有{字符
isJSON_test('[{},"2"]'); //数组 :子项包含对象
isJSON_test('[[{},{"2":"3"}],"2"]'); //多维数组
测试结果如下:
结论
如果JSON.parse能够转换成功;并且转换后的类型为object 且不等于 null,那么这个字符串就是JSON格式的字符串。
更多推荐
已为社区贡献1条内容
所有评论(0)