问题描述
我想从我的localStorage导出一些项目,以便在外部保存,但格式可以稍后重新导入。
I want to export a few items from my localStorage to save it externally but in a format so that I can import it again later.
我试图写可以在稍后在textarea中粘贴的可执行代码。那么该文本的值将只是eval()ed。
My attempt was to write executable code that can be pasted later in a textarea. Then the value of that textare will simply be eval()ed.
问题:存储在localStorage中的数据存储为
Problem: The data stored in localStorage were stored as
var data = [];
data.push('sampledata');
data.push({sample: 'object'});
localStorage.setItem('varname',data);
所以它包含我不喜欢的各种字符,如,等等
So it contains various chars I don't like, like ', " 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?
推荐答案
您可以使用JSON.parse(字符串对象)和JSON.stringify(对象到字符串)将localStorage项编码为字符串
You can encode localStorage items into strings using JSON.parse (string to object) and JSON.stringify (object to string)
阅读fr om localStorage
Read from localStorage
var strValue = JSON.stringify(localStorage.getItem("varname"));
写入localStorage
Write to localStorage
localStorage.setItem("varname",JSON.parse(strValue));
这篇关于导出localStorage中的数据以供以后重新导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!