简体   繁体   中英

localStorage: Storing Objects vs Simple Data Types in different ways?

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.

There's no way to know whether a string your retrieve is intended to be a serialized object or a plain string, except based on your own rules . The strings "null" , "34" , "[1,2,3]" could all be valid strings or valid JSON, and unless you have an idea of expected content there is no way to be sure.

So I'd suggest either:

  • Serialize and deserialize everything. This shouldn't be too bad performance-wise unless you're doing it at very high frequencies (in which case maybe localStorage is the wrong choice).

OR

  • Add a custom "header" to your serialized strings, eg "JSON:{...}" . Then, when you retrieve a string, check for the header and process accordingly.
lsSet: function(key, value) {
  switch(typeof value){
      case "string" : localStorage.setItem(key,'"' + value + '"'); break;
      case "number" : localStorage.setItem(key,value); break;
      case "object" : localStorage.setItem(key,JSON.stringify(value)); break;
  }
  return (localStorage.getItem(key)) ? true : false;
},

just an idea not tested

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM