<分区>
我有一个通过 JSON.Stringify 函数从对象转换而来的 json 字符串。
我想知道它是 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'));