js判断是否是Json对象

来源:互联网 发布:华通云数据与马云关系 编辑:程序博客网 时间:2024/05/19 12:14

有两种方法

1.使用正则表达式(推荐),代码如下:

if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {  //the json is ok}else{  //the json is not ok}

2.使用try-catch

function IsJsonString(str) {    try {        JSON.parse(str);    } catch (e) {        return false;    }    return true;}
0 0
原创粉丝点击