我有一个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)