js判断字符串是否为JSON格式
2024-09-04 03:09:25
不能简单地使用来判断字符串是否是JSON格式:
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'); //
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
详细的描述见:https://segmentfault.com/q/1010000008460413
我们可以使用如下的方法来判断:
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!')
} console.log('123 is json? ' + isJSON('123'))
console.log('{} is json? ' + isJSON('{}'))
console.log('true is json? ' + isJSON('true'))
console.log('foo is json? ' + isJSON('"foo"'))
console.log('[1, 5, "false"] is json? ' + isJSON('[1, 5, "false"]'))
console.log('null is json? ' + isJSON('null'))
console.log('["1{211323}","2"] is json? ' + isJSON('["1{211323}","2"]'))
console.log('[{},"2"] is json? ' + isJSON('[{},"2"]'))
console.log('[[{},{"2":"3"}],"2"] is json? ' + isJSON('[[{},{"2":"3"}],"2"]'))
运行结果为:
> "123 is json? false"
> "{} is json? true"
> "true is json? false"
> "foo is json? false"
> "[1, 5, "false"] is json? true"
> "null is json? false"
> "["1{211323}","2"] is json? true"
> "[{},"2"] is json? true"
> "[[{},{"2":"3"}],"2"] is json? true"
上面的这段代码来自:https://www.cnblogs.com/lanleiming/p/7096973.html。 文章中有详细的描述,代码的正确性。
JSON数据格式,主要由对象 { } 和数组 [ ] 组成。平时中我们用的基本上是对象,但是我们不能忘了数组也是json的数据格式。例如[ "Google", "Runoob", "Taobao" ]。
JSON 数组在中括号中书写。
JSON 中数组值必须是合法的 json数据类型(字符串, 数字, 对象, 数组, 布尔值或 null)。
最新文章
- AngularJS下拉列表select在option动态变化之后多出了一个错误项的问题
- VB下对HTML元素的操作
- Fragment:关于Avoid non-default constructors in fragments的错误
- Python之路-python(装饰器、生成器、迭代器、Json &; pickle 数据序列化、软件目录结构规范)
- Android 利用日志消息调试程序
- PHP中的session
- 查看jdk的位数
- 【HDOJ】1099 Lottery
- POJ3318【随机化算法挺有意思】
- This compilation unit is not on the build path SVN
- 在linux下,怎么去查看一个运行中的程序, 到底是占用了多少内存
- vs 2017 vs code
- VS code 设置中文后也显示英文的问题
- 我为什么要写 blog?
- ipcam
- [Selenium With C#基础教程] Lesson-01环境搭建
- Java虚拟机--线程安全和锁优化
- Intellij IDEA打开就闪退或关闭
- SVN服务器多个项目的权限分组管理
- 使用ABP框架踩过的坑系列1
热门文章
- ThinkPHP3.2.2 无刷新上传插件uploadify 使用
- maven项目bulid失败_No compiler is provided in this environment.
- 决策树--CART树详解
- BOOST 解析,修改,生成xml样例
- vue 运行脚手架报错
- 实现同时将一批.bmp文件转换成.mat格式
- TCP连接创建与终止
- Codeforces 785 E. Anton and Permutation(分块,树状数组)
- P1914 小书童——密码
- [CSP-S模拟测试]:序列(二分答案+树状数组)