function isJSON(str) {
    if (typeof str != 'string') { // 1、传入值必须是 字符串
        console.log('It is not a string! [' + str + ']')
        return false;
    }

    try {
        var obj = JSON.parse(str); // 2、仅仅通过 JSON.parse(str),不能完全检验一个字符串是JSON格式的字符串
        if (typeof obj == 'object' && obj) {  //3、还必须是 object 类型
            console.log('转换成功:' + str);
            return true;
        } else {
            console.log('转换失败:' + str);
            return false;
        }

    } catch (e) {
        console.log('error:[' + str + '] !!! ' + e);
        return false;
    }
    return false;
}

测试代码:

isJSON('123');              // number
isJSON('aaaa');             // string
isJSON('"aaa"');
isJSON('true');             // 布尔
isJSON('["1","2"]');        // 数组
isJSON('["1{211323}","2"]'); // 数组 :含有{字符
isJSON('[{},"2"]');         // 数组 :子项包含对象
isJSON('[[{},{"2":"3"}],"2"]'); // 多维数组

isJSON('{name:"123"}');     // 对象
isJSON('{"name":"123"}');   // json
isJSON('{"name":"123",}');  // 不规范的json

isJSON('{}');               // 空对象
isJSON('null');             // null
isJSON('Undefined');        // Undefined

运行结果:
在这里插入图片描述

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐