js判断一个字符串是不是json格式

因为JSON.parse()有特例

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

segmentfault 上的提问和回答:https://segmentfault.com/q/1010000008460413

验证有效的参考:https://www.cnblogs.com/lanleiming/p/7096973.html

//判断一个字符串是不是json格式
 let isJSON = function(str) {
    if(typeof(str) === 'string') {
        try{
            var obj = JSON.parse(str);
            if(typeof(obj) === 'object' && obj) {
                return true;
            }
            else {
                return false;
            }
        }
        catch(e) {
            return false;
        }
    }
} 
export default isJSON;

你可能感兴趣的:(原生JS练习)