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'));
If you have var a = 1 and var var b = "1" then typeof a is number and typeof b is string , both a and b can be passed to JSON. parse and it would result in 1 , but only b is in this case JSON, because it is a string based representation of the number 1 .
To check if a string is JSON in JavaScript, we can use the JSON. parse method within a try-catch block. to check if jsonStr is a valid JSON string. Since we created the JSON string by calling JSON.
JSON is purely a string with a specified data format — it contains only properties, no methods. JSON requires double quotes to be used around strings and property names.
We can have duplicate keys in a JSON object, and it would still be valid.
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;}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With