How to check if it's a string or json
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;}
you can easily make one using JSON.parse
. When it receives a not valid JSON string it throws an exception.
function isJSON(data) {
var ret = true;
try {
JSON.parse(data);
}catch(e) {
ret = false;
}
return ret;
}
Found this in another post How do you know if an object is JSON in javascript?
function isJSON(data) {
var isJson = false
try {
// this works with JSON string and JSON object, not sure about others
var json = $.parseJSON(data);
isJson = typeof json === 'object' ;
} catch (ex) {
console.error('data is not JSON');
}
return isJson;
}