I've seen the approach of using JSON.stringify and JSON.parse to store and retrieve values/objects from HTML5 localStorage. It works, but it "stringifies" everything - including strings, numbers, etc. I'd like to improve it. I'd like to avoid "stringifying" simple data types that are not objects. I've got a method below that I use to determine if a parameter is an object and JSON.stringify it if it is an object.
lsSet: function(key, value) {
((Object.prototype.toString.call(value) === '[object Object]'))
? localStorage.setItem(key,JSON.stringify(value))
: localStorage.setItem(key,value);
return (localStorage.getItem(key)) ? true : false;
},
Is there a good way to identify if a localStorage string you are retrieving is a stringified object? I was thinking of checking if the string starts with { and ends with }, but it seems like there must be a better approach. Below is my current localStorage get method, but throws errors when trying to JSON.parse simple data types such as string.
lsGet: function(key) {
return JSON.parse(localStorage.getItem(key));
},
Typical console error is due to to the JSON.parse:
Uncaught SyntaxError: Unexpected token E
Any ideas? A thought just came to mind, maybe just a try/catch?
var value;
try {
value = JSON.parse(localStorage.getItem(key));
} catch(err) {
value = localStorage.getItem(key);
}
return value;
Edit: Note, I'm juggling a lot of different data around and I don't really want to have to worry about the typeof data I'm setting/getting. Thus stardard lsSet/lsGet methods were created. In my app, data is stored in PHP Session, JavaScript Objects and localStorage - a bit of a mix.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…