在我正在处理的程序中,我使用JSON.stringify将文字变量发送到本地存储区。计划是我想不断更新本地存储并添加到现有的本地存储。我遇到了JSON文件解析方面的问题。我添加到存储的代码是:
function addtoStorage(key, data) {
if (typeof(Storage) !== "undefined") {
if (localStorage[key]) {
console.log("Local Storage stuff" + localStorage[key]);
var olddata = JSON.parse(localStorage[key]);
var dataJSON = JSON.stringify(olddata + data);
localStorage[key] = localStorage[key] + dataJSON;
}
else {
var dataJSON = JSON.stringify(data);
localStorage[key] = dataJSON;
}
}
else {
console.log("You don't have storage capabilities. Sorry. Next time improve your browser.");
}
} ;
我的输出是在console.log上的:
Local Storage stuff{"asdf":"","tes":6,"type":"asdf","ast":1,"sd":"","ew":"","asdf":{"te":0,"wer":0},"asf":"","te":"","context":{"asdf":1,"total_hits":0,"asdf":1,"tew":0,"asdf":"","tes":"","date":"asfd-asdf-","asdf":0},"asdf":""}"[object Object][object Object]" main.js:487
未捕获的SyntaxError:意外的字符串
我很确定我明白问题所在。我似乎无法弄清楚如何解决它。它显然很快关闭了JSON对象,任何建议???
答案 0 :(得分:3)
我不认为你应该做olddata + data
,因为stringify
用于将JavaScript对象解析为JSON,你不能只将两个对象一起添加。
你应该尝试实现一个对象合并函数,就像jQuery使用的那样:
function merge( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
for ( ; j < len; j++ ) {
first[ i++ ] = second[ j ];
}
first.length = i;
return first;
}
然后就这样做
var newdata = merge(olddata, data);
var dataJSON = JSON.stringify(newdata);
https://github.com/jquery/jquery/blob/master/src/core.js#L390
答案 1 :(得分:1)
Uncaught SyntaxError: Unexpected string
来自JSON.parse
,这是因为它不再是有效的JSON(http://json.org/)
您正在做的是向对象添加一个对象,结果是一个字符串
然后当你去字符串化时,整个事情将只是第一次和第二次的字符串。所以它会很好,然后第三次尝试解析它时,函数将失败,因为你已经添加了一个带字符串的JSON对象。
如果您只存储JSON对象,则可以使用jQuery的扩展函数(http://api.jquery.com/jQuery.extend/)
或者,如果您要存储更多,则只需将对象全部更改为数组
这应涵盖所有内容
function addtoStorage(key, data) {
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem(key)) {
console.log("Local Storage stuff" + localStorage.getItem(key));
var olddata = JSON.parse(localStorage.getItem(key));
var newdata = null;
if(olddata instanceof Array){
olddata.push(data);
newdata = olddata;
}else if(data instanceof Array || !(data instanceof Object) || !(olddata instanceof Object)){
newdata = [olddata, data];
}else if(data instanceof Object && olddata instanceof Object){
newdata = $.extend(olddata, data);
}
var dataJSON = JSON.stringify(newdata);
localStorage.setItem(key, dataJSON);
}
else {
var dataJSON = JSON.stringify(data);
localStorage.setItem(key, dataJSON);
}
}
else {
console.log("You don't have storage capabilities. Sorry. Next time improve your browser.");
}
}