【最简单的方法】js判断字符串是否为JSON格式(20180115更新)
2017-06-30 00:49
701 查看
前言
针对“js判断字符串是否为JSON格式”这个问题,在网上查了许多资料,都没找到自己想要的答案。但是看到这个帖子
如果你对这个方法有异议,欢迎留言探讨。
解决方案
V2.0版---感谢@年少轻狂识@marihees的提醒,已经对代码进行了更新
functionisJSON(str){ if(typeofstr=='string'){ try{ varobj=JSON.parse(str); if(typeofobj=='object'&&obj){ returntrue; }else{ returnfalse; } }catch(e){ console.log('error:'+str+'!!!'+e); returnfalse; } } console.log('Itisnotastring!') }
v1.0不严谨,已废弃。 functionisJSON(str){ if(typeofstr=='string'){ try{ varobj=JSON.parse(str); if(str.indexOf('{')>-1){ returntrue; }else{ returnfalse; } }catch(e){ console.log(e); returnfalse; } } returnfalse; }
分析
就像之前的帖子所说,只是单纯的用JSON.parse(str)不能完全检验一个字符串是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
我们知道,JS中的数据类型分为:字符串、数字、布尔、数组、对象、Null、Undefined。
那我们就针对这几种类型的字符串进行测试。
functionisJSON_test(str){ if(typeofstr=='string'){ try{ varobj=JSON.parse(str); console.log('转换成功:'+obj); returntrue; }catch(e){ console.log('error:'+str+'!!!'+e); returnfalse; } } console.log('Itisnotastring!') }
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
----v2.0新增测试-----
isJSON_test('["1{211323}","2"]');//数组:含有{字符
isJSON_test('[{},"2"]');//数组:子项包含对象
isJSON_test('[[{},{"2":"3"}],"2"]');//多维数组
测试结果如下图:
V1.0
从以上测试结果,以及JSON的定义。可以得到一个规律:
如果JSON.parse能够转换成功;并且字符串中包含{时,那么这个字符串就是JSON格式的字符串。
V2.0
以上测试结果,能够转换成功的有:数字、字符串、布尔、数组、空对象、null、json。
其中正确的JSON格式有:数组、空对象、json
所以得出以下结论:
如果JSON.parse能够转换成功;并且转换后的类型为object且不等于null,那么这个字符串就是JSON格式的字符串。
如果大家对这个方法有异议,欢迎在下方留言,感谢。