Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
684 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, e.g. "JSON:{...}". Then, when you retrieve a string, check for the header and process accordingly.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...