Export data to localStorage for subsequent re-import

I want to export several items from my local storage in order to save it from the outside, but in a format so that I can import it later.

My attempt was to write executable code that can be inserted later in a text box. Then the value of this textare will be just eval () ed.

Problem: Data stored in localStorage was saved as

var data = []; data.push('sampledata'); data.push({sample: 'object'}); localStorage.setItem('varname',data); 

Thus, it contains various characters that I do not like, for example, "," etc.

My (not working) solution so far:

 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 in order, what is the best way to create the code, which can then be executed as it is?

+5
source share
3 answers

You can encode objects to strings using JSON.stringify (object to string), and decode strings to 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")); 
+8
source

Here's how to import / export your entire localStorage

export

 copy(JSON.stringify(localStorage)); 

This will copy your localStorage to the clipboard. (You need two JSON.stringify () to escape quotes.)

Import

 var data = JSON.parse(/*paste stringified JSON from clipboard*/); Object.keys(data).forEach(function (k) { localStorage.setItem(k, data[k]); }); 
+23
source

Just an improved version of Jeremy. Simplify the process

 copy('var data = '+JSON.stringify(localStorage)+';Object.keys(data).forEach(function (k){localStorage.setItem(k, data[k]);});'); 

Run it in the console where you need to export, it will copy the contents of localalstorage along with the code to the clipboard and just paste it into the console where you want to import.

0
source

Source: https://habr.com/ru/post/1445398/


All Articles