zoukankan      html  css  js  c++  java
  • [转]JS判断字符串是否为json数据

    原文地址: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;
        }
    如果解析出来的结果类型是一个对象,说明解析成功,如果是其他的类型,说明解析失败了

  • 相关阅读:
    python 之字符编码
    python文件处理
    迭代器和生成器
    内置函数和匿名函数
    函数之递归
    函数 之装饰器
    python 函数进阶与闭包
    python 之 函数
    python之运算符
    python字符串内置方法
  • 原文地址:https://www.cnblogs.com/dirgo/p/10762135.html
Copyright © 2011-2022 走看看