如何检查它是字符串还是json [英] How to check if it's a string or json
本文介绍了如何检查它是字符串还是json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个json字符串,它是通过JSON.Stringify函数从对象转换而来的。
I have a json string that is converted from object by JSON.Stringify function.
我想知道它是json字符串还是只是一个常规字符串。
I'd like to know if it's json string or just a regular string.
是否有像isJson()这样的函数来检查它是否是json?
Is there any function like "isJson()" to check if it's json or not?
我是我喜欢在使用本地存储时使用该功能,如下面的代码。
I'd like to use the function when I use local storage like the code below.
提前谢谢!!
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'));
推荐答案
简单的方法是尝试
解析并在失败时返回未解析的字符串:
The "easy" way is to try
parsing and return the unparsed string on failure:
var data = localStorage[key];
try {return JSON.parse(data);}
catch(e) {return data;}
这篇关于如何检查它是字符串还是json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文