I want to export a few items from my localStorage to save it externally however, I'd like these items in a format so that I can import it again later.
My attempt was to write executable code that can be pasted later in a textarea. Then the value of that textarea will simply be evaluated using eval().
Problem: The data stored in localStorage were stored as:
var data = [];
data.push('sampledata');
data.push({sample: 'object'});
localStorage.setItem('variable_name', data);
So it contains various chars I don't like, i.e. ', " etc.
My (not working) solution so far was:
var container = $('#localDataContainer');
container.append('localStorage.setItem("cockpitLastVisited","' + localStorage.getItem("cockpitLastVisited") + '");<br/>');
container.append('localStorage.setItem("cockpit_services","' + localStorage.getItem("cockpit_services") + '");<br/>');
container.append('localStorage.setItem("cockpit_users","' + localStorage.getItem("cockpit_users") + '");');
If my attempt seems to be OK, what is the best way to create code that can then be executed the way it is?
You can encode Objects into Strings using JSON.stringify (object to String) and decode Strings into Objects using JSON.parse (String to Object).
Write to localStorage
localStorage.setItem("varname",JSON.stringify(originalVarname));
Read from localStorage
var originalVarname= JSON.parse(localStorage.getItem("varname"));