lnlvinso

      不能简单地使用来判断字符串是否是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\'); // 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)。

       

  

分类:

技术点:

相关文章: