I have a json string that is converted from object by JSON.Stringify function.
I'd like to know if it's json string or just a regular string.
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.
Thank you in advance!!
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'));
I think returning parsed JSON at the same time is a good idea, so I prefer following version:
As you probably know
JSON.parse("1234")
,JSON.parse("0")
,JSON.parse("false")
andJSON.parse("null")
won't raise Exception and will return true. all this values are valid JSON but if you want to seeisValid
istrue
only for objects (e.g:{ "key": "value" }
) and arrays (e.g:[{ "key": "value" }]
) you can use following version:The "easy" way is to
try
parsing and return the unparsed string on failure:Found this in another post How do you know if an object is JSON in javascript?
you can easily make one using
JSON.parse
. When it receives a not valid JSON string it throws an exception.Since the question is "How to check if it's a string or json" maybe a simple way would be to check for string, so you would have done something like this somewhere:
Maybe that could be enough depending on your overall solution, just in case someone else is looking around.