Javascript之判断一个字符串是否是json

原文链接: https://www.cnblogs.com/lanleiming/p/7096973.html

本文主要参考自:https://www.cnblogs.com/lanleiming/p/7096973.html

整理至自己博客近做留存。

说明:

    只是单纯的用JSON.parse(str)不能完全检验一个字符串是JSON格式的字符串。单纯的字符串,boolean类型的变量也可以被成功解析。

 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

 

因此,需要对解析完对变量做类型判断,只有当parse之后的变量存在且类型为对象时,才认为字符串是一个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) {
            console.log('error:'+str+'!!!'+e);
            return false;
        }
    }
    console.log('It is not a string!')
}

 

你可能感兴趣的:(JavaScript日记)