我使用JSON.stringify()将javascript对象保存到localstorage。
localStorage.setItem('stored_object', JSON.stringify(objCases) );
我会发现json字符串已经自发地从中自发地改变了:
{"9999999999999":{"case":"dummy","subj":"example","note":"placeholder"}}
进入:
{asynchronous_key:'577b3620-8cbd-5251-b526-5882044f1386', jsonObject:{"\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039":{"\u0063\u0061\u0073\u0065":"\u0064\u0075\u006d\u006d\u0079","\u0073\u0075\u0062\u006a":"\u0065\u0078\u0061\u006d\u0070\u006c\u0065","\u006e\u006f\u0074\u0065":"\u0070\u006c\u0061\u0063\u0065\u0068\u006f\u006c\u0064\u0065\u0072"}}}
在another question中,用户GoTo 0
提供了解决方案,但我很难实现它。我想我错过了一些基本的东西:
Stack Snippet示例:
var badjson = {asynchronous_key:'49098507-12cd-e1b0-b442-5882cd1bf37e', jsonObject:{"\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039":{"\u0063\u0061\u0073\u0065":"\u0064\u0075\u006d\u006d\u0079","\u0073\u0075\u0062\u006a":"\u0065\u0078\u0061\u006d\u0070\u006c\u0065","\u006e\u006f\u0074\u0065":"\u0070\u006c\u0061\u0063\u0065\u0068\u006f\u006c\u0064\u0065\u0072"}}};
localStorage.setItem('remindObj', JSON.stringify(badjson));
console.log('Here 03: '+ localStorage.getItem('remindObj') );
var getjson = localStorage.getItem('remindObj');
console.log('Here 06: ' +getjson);
console.log(typeof(getjson));
console.log(getjson.indexOf('asynchronous_key') );
if (getjson.indexOf('asynchronous_key') > 0){
console.log('ASYNCHRONOUS_KEY FOUND - Attempting to fix');
originalJSONString = JSON.stringify(getjson.jsonObject);
console.log('FIXING: ' +originalJSONString);
objRemind = JSON.parse(originalJSONString);
localStorage.setItem("remindObj", originalJSONString);
console.log('FIXED: ' +localStorage.getItem("remindObj") );
}
答案 0 :(得分:0)
这样你就可以关闭它:第11行有一个错误(计算空行):它应该是JSON.parse()
而不是JSON.stringify()
编辑小提琴:https://jsfiddle.net/4n6dqqvn/1/
var storageKey = 'remindObj';
var badjson = {
asynchronous_key: '49098507-12cd-e1b0-b442-5882cd1bf37e',
jsonObject:{
"\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039\u0039":{
"\u0063\u0061\u0073\u0065":"\u0064\u0075\u006d\u006d\u0079","\u0073\u0075\u0062\u006a":"\u0065\u0078\u0061\u006d\u0070\u006c\u0065",
"\u006e\u006f\u0074\u0065":"\u0070\u006c\u0061\u0063\u0065\u0068\u006f\u006c\u0064\u0065\u0072"
}
}
};
localStorage.setItem(storageKey, JSON.stringify(badjson));
var getjson = localStorage.getItem(storageKey);
console.log('Initial: ', getjson);
if (typeof(getjson) === 'string'){
console.log('ASYNCHRONOUS_KEY FOUND - Attempting to fix');
var originalJSONString = JSON.parse(getjson).jsonObject;
console.log('FIXING: ', originalJSONString);
localStorage.setItem(storageKey, JSON.stringify(originalJSONString));
console.log('FIXED: ', JSON.parse(localStorage.getItem(storageKey)));
}