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

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

这周碰到了不少问题,尽可能把遇到的问题都记录下来。

  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;
    }
若是解析出来的结果类型是一个对象,说明解析成功,若是是其余的类型,说明解析失败了

segmentfault

相关文章
相关标签/搜索