Reputation: 14510
Sorry if the title is somehow misunderstanding. I am having some problems with a web app if I try to parse values from a localstorage using json and there are no values, nothing works.
For example:
If you do this: alert(localStorage.getItem("something"));
you get null: http://jsfiddle.net/yrGht/
but if you do this it blocks everything: alert(JSON.parse(localStorage["test"]));
you get nothing and it stops everything from working: http://jsfiddle.net/7tCaS/
How can I solve this so that I alert the first and if it has no value then keep working because basically I want to set this: JSON.parse(localStorage["test"])
as a global variable but it blocks everything else: http://jsfiddle.net/gq9Ea/
Upvotes: 3
Views: 6876
Reputation: 708156
When using localStorage, you need to anticipate in your coding that the data might not be there and you need to test for that condition and handle it in some way. The simplest way to do that would be something like this:
var rawData = localStorage.getItem("something");
var parsedData = {}; // set whatever the default value should be if there is no localStorage value
if (rawData) {
parsedData = JSON.parse(rawData);
}
You could also use exception handling:
var parsedData;
try {
parsedData = JSON.parse(localStorage.getItem("something"));
} catch(e) {
parsedData = {}; // set default value if localStorage parsing failed
}
In addition, you should learn how to see your javascript errors in the browser error console or the debugger console. Javascript wasn't "blocked". It threw an error which was unhandled so execution was aborted. That error (both line number and type of error) was logged in both the error console and the debugger console for you to see.
Upvotes: 2
Reputation: 324830
Try this:
alert(JSON.parse(localStorage['test'] || null));
The reason it fails is because JSON.parse(undefined_variable)
gives an "invalid character" error. If localStorage['test']
doesn't exist, it's undefined
, so it gets an error. The above code puts null
in place if the value is falsy, which undefined
is. However this does have ill effects if the value is 0
, ""
or another falsy value. If more specific code is needed, try:
alert(JSON.parse(typeof localStorage['test'] == "undefined" ? null : localStorage['test']));
Upvotes: 7