js判断字符串是否为json

typeof JSON.parse() == 'object'  当字符串不是json时报错判断不出来,故而用try catch  不报错则为json

代码

/**
     * 判断是否json
     * @param $string
     * @returns {boolean}
     */
    function isJson($string)
    {
        try {
            if(typeof JSON.parse($string) == 'object')
                return true;
            return false;
        } catch (e) {
            console.log(e);
            return false;

        }
    }
发布了85 篇原创文章 · 获赞 45 · 访问量 95万+

猜你喜欢

转载自blog.csdn.net/flysnownet/article/details/99818412