相关疑难解决方法(0)

如何检查它是字符串还是json

我有一个json字符串,由JSON.Stringify函数从对象转换而来.

我想知道它是json字符串还是只是一个常规字符串.

是否有像"isJson()"这样的函数来检查它是否是json?

当我使用本地存储时,我想使用该功能,如下面的代码.

先感谢您!!

var Storage = function(){}

Storage.prototype = {

  setStorage: function(key, data){

    if(typeof data == 'object'){

      data = JSON.stringify(data);
      localStorage.setItem(key, data);     

    } else {
      localStorage.setItem(key, data);
    }

  },


  getStorage: function(key){

    var data = localStorage.getItem(key);

    if(isJson(data){ // is there any function to check if the argument is json or string?

      data = JSON.parse(data);
      return data;

    } else {

      return data;
    }

  }

}

var storage = new Storage();

storage.setStorage('test', {x:'x', y:'y'});

console.log(storage.getStorage('test'));
Run Code Online (Sandbox Code Playgroud)

javascript jquery json

15
推荐指数
3
解决办法
2万
查看次数

标签 统计

javascript ×1

jquery ×1

json ×1