针对 “js判断字符串是否为JSON格式” 这个问题,在网上查了许多资料,都没找到自己想要的答案。
但是看到这个帖子《js判断字符串是否为JSON格式》后,突然灵光一闪,想到一种很简单的解决方案。
如果你对这个方法有异议,欢迎留言探讨。
function isJSON(str) {if (typeof str == 'string') {try {var obj=JSON.parse(str);if(str.indexOf('{')>-1){return true;
}else{return false;
}
} catch(e) {
console.log(e);return false;
}
}return false;
} 就像之前的帖子所说,只是单纯的用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。
那我们就针对这几种类型的字符串进行测试。
<span style="font-size: 16px;"><span style="color: #0000ff;">function</span><span style="color: #000000;"> isJSON_test(str) {</span><span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">typeof</span> str == 'string'<span style="color: #000000;">) {</span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {</span><span style="color: #0000ff;">var</span> obj=<span style="color: #000000;">JSON.parse(str);
console.log(</span>'转换成功:'+<span style="color: #000000;">obj);</span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">true</span><span style="color: #000000;">;
} </span><span style="color: #0000ff;">catch</span><span style="color: #000000;">(e) {
console.log(</span>'error:'+str+'!!!'+<span style="color: #000000;">e);</span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">false</span><span style="color: #000000;">;
}
}
console.log(</span>'It is not a string!'<span style="color: #000000;">)
}</span><em> <br/></em></span><span style="font-size: 16px;">isJSON_test('123'); //number</span><br/><span style="font-size: 16px;">isJSON_test('aaaa'); //string</span><br/><span style="font-size: 16px;">isJSON_test('"aaa"');</span><br/><span style="font-size: 16px;">isJSON_test('true'); //布尔</span><br/><span style="font-size: 16px;">isJSON_test('["1","2"]'); //数组</span><br/><span style="font-size: 16px;">isJSON_test('{name:"123"}'); //对象</span><br/><span style="font-size: 16px;">isJSON_test('{}'); //空对象</span><br/><span style="font-size: 16px;">isJSON_test('null'); //null</span><br/><span style="font-size: 16px;">isJSON_test('Undefined'); //Undefined</span><br/><span style="font-size: 16px;">isJSON_test('{"name":"123"}'); //json</span><br/><span style="font-size: 16px;"><em>isJSON_test('{"name":"123",}'); //不规范的json</em></span>
测试结果如下图:

Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
从以上测试结果,以及JSON的定义 。可以得到一个规律:
如果JSON.parse能够转换成功;并且字符串中包含 { 时,那么这个字符串就是JSON格式的字符串。
如果大家对这个方法有异议,欢迎在下方留言,感谢。
以上就是js怎么判断字符串为JSON格式?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号