[转]JS判断字符串是否为json数据

时间:2022-03-08 05:19:28

原文地址:https://blog.csdn.net/qq_26400953/article/details/77411520

这周碰到了很多问题,尽量把遇到的问题都记录下来。

JS判断字符串是否为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!')    
}
这样是不是就可以了呢?测试的时候输入“123”,居然过了,所以是有问题的,于是找到了segmentfault上的一篇问答  https://segmentfault.com/q/1010000008460413/a-1020000008461292 里面也给出了一些解决方案。
  下面是博主师傅给出的解决方案:

function isJsonString(str) {
        try {
            if (typeof JSON.parse(str) == "object") {
                return true;
            }
        } catch(e) {
        }
        return false;
    }
如果解析出来的结果类型是一个对象,说明解析成功,如果是其他的类型,说明解析失败了