我想在HTML5 localStorage中存储一个JavaScript对象,但我的对象显然被转换为字符串。

我可以使用localStorage存储和检索原始JavaScript类型和数组,但对象似乎不起作用。他们应该吗?

这是我的代码:

var testObject = { 'one': 1, 'two': 2, 'three': 3 };
console.log('typeof testObject: ' + typeof testObject);
console.log('testObject properties:');
for (var prop in testObject) {
    console.log('  ' + prop + ': ' + testObject[prop]);
}

// Put the object into storage
localStorage.setItem('testObject', testObject);

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

console.log('typeof retrievedObject: ' + typeof retrievedObject);
console.log('Value of retrievedObject: ' + retrievedObject);

控制台输出为

typeof testObject: object
testObject properties:
  one: 1
  two: 2
  three: 3
typeof retrievedObject: string
Value of retrievedObject: [object Object]

在我看来,setItem方法在存储输入之前将其转换为字符串。

我在Safari、Chrome和Firefox中看到了这种行为,所以我认为这是我对HTML5 Web存储规范的误解,而不是浏览器特定的错误或限制。

我已经试图理解2公共基础设施中描述的结构化克隆算法。我不完全理解它的意思,但也许我的问题与对象的财产不可枚举有关(???)。

有简单的解决方法吗?


更新:W3C最终改变了对结构化克隆规范的想法,并决定更改规范以匹配实现。请参阅12111–存储对象getItem(key)方法的规范与实现行为不匹配。因此,这个问题不再100%有效,但答案可能仍然令人感兴趣。


当前回答

您可以使用ejson将对象存储为字符串。

EJSON是JSON的扩展,以支持更多类型。它支持所有JSON安全类型,以及:日期(JavaScript日期)二进制(JavaScript Uint8Array或EJSON.newBinary的结果)用户定义的类型(请参阅EJSON.addType。例如,Mongo.ObjectID就是这样实现的。)所有EJSON序列化也是有效的JSON。例如,具有日期和二进制缓冲区的对象将在EJSON中序列化为:{“d”:{“$date”:1358205756553},“b”:{“$binary”:“c3VyZS4=”}}

这是我使用ejson的localStorage包装器

https://github.com/UziTech/storage.js

我在包装器中添加了一些类型,包括正则表达式和函数

其他回答

我在读到另一篇文章后发表了这篇文章,这篇文章的标题是“如何在本地存储中存储数组?”。这很好,除了两个线程都没有提供关于如何在localStorage中维护数组的完整答案之外,不过我已经根据两个线程中包含的信息制定了一个解决方案。

因此,如果其他人希望能够在数组中推送/弹出/移动项目,并且他们希望将该数组存储在localStorage或sessionStorage中,那么可以这样做:

Storage.prototype.getArray = function(arrayName) {
  var thisArray = [];
  var fetchArrayObject = this.getItem(arrayName);
  if (typeof fetchArrayObject !== 'undefined') {
    if (fetchArrayObject !== null) { thisArray = JSON.parse(fetchArrayObject); }
  }
  return thisArray;
}

Storage.prototype.pushArrayItem = function(arrayName,arrayItem) {
  var existingArray = this.getArray(arrayName);
  existingArray.push(arrayItem);
  this.setItem(arrayName,JSON.stringify(existingArray));
}

Storage.prototype.popArrayItem = function(arrayName) {
  var arrayItem = {};
  var existingArray = this.getArray(arrayName);
  if (existingArray.length > 0) {
    arrayItem = existingArray.pop();
    this.setItem(arrayName,JSON.stringify(existingArray));
  }
  return arrayItem;
}

Storage.prototype.shiftArrayItem = function(arrayName) {
  var arrayItem = {};
  var existingArray = this.getArray(arrayName);
  if (existingArray.length > 0) {
    arrayItem = existingArray.shift();
    this.setItem(arrayName,JSON.stringify(existingArray));
  }
  return arrayItem;
}

Storage.prototype.unshiftArrayItem = function(arrayName,arrayItem) {
  var existingArray = this.getArray(arrayName);
  existingArray.unshift(arrayItem);
  this.setItem(arrayName,JSON.stringify(existingArray));
}

Storage.prototype.deleteArray = function(arrayName) {
  this.removeItem(arrayName);
}

示例用法-在localStorage数组中存储简单字符串:

localStorage.pushArrayItem('myArray','item one');
localStorage.pushArrayItem('myArray','item two');

示例用法-在sessionStorage阵列中存储对象:

var item1 = {}; item1.name = 'fred'; item1.age = 48;
sessionStorage.pushArrayItem('myArray',item1);

var item2 = {}; item2.name = 'dave'; item2.age = 22;
sessionStorage.pushArrayItem('myArray',item2);

处理数组的常用方法:

.pushArrayItem(arrayName,arrayItem); -> adds an element onto end of named array
.unshiftArrayItem(arrayName,arrayItem); -> adds an element onto front of named array
.popArrayItem(arrayName); -> removes & returns last array element
.shiftArrayItem(arrayName); -> removes & returns first array element
.getArray(arrayName); -> returns entire array
.deleteArray(arrayName); -> removes entire array from storage

循环引用

在这个答案中,我专注于具有循环引用的仅数据对象(没有函数等),并开发maja和mathheadinclouds提到的想法(我使用了他的测试用例和我的代码短了几倍)。

实际上,我们可以使用带有适当替换符的JSON.stringify-如果源对象包含对某个对象的多个引用,或者包含循环引用,那么我们可以通过特殊路径字符串(类似于JSONPath)来引用它。

//JSON.strify具有circ-ref的对象的替换器函数refReplacer(){设m=new Map(),v=new Map),init=null;返回函数(字段,值){让p=m.get(this)+(Array.isArray(this)`[${field}]“:”.“+字段);让isComplex=value==对象(值)如果(isComplex)m.set(值,p);让pp=v.get(value)||'';let path=p.replace(/未定义\.\?/,“”);让val=pp`#REF:${pp[0]==“[”?“$”:“$.”}${pp}“:value;!初始化?(init=value):(val===init?val=“#REF:$”:0);if(!pp&&isComplex)v.set(value,path);返回值;}}// ---------------//测试// ---------------//生成具有重复/循环引用的obj让obj={我:{五十: {v:“lorem”},R: {v:“ipsum”}},R:{五十: {v:“dolor”},R:{五十: {v:“坐”},R: {v:“amet”}}}}obj.R.L.uncle=对象L;obj.R..uncle=对象L;obj.R.L..uncle=obj.R.L;obj.R.R..uncle=obj.R.L;obj.L.L.uncle=对象R;obj.L.R.unncle=对象R;testObject=obj;让json=json.stringify(testObject,refReplacer(),4);console.log(“测试对象\n”,testObject);console.log(“带有JSONpath引用的JSON”,JSON);

使用类似JSONpath的引用解析此类JSON内容:

//使用对象的JSONpath引用解析JSON内容函数parseRefJSON(json){let objToPath=新映射();let pathToObj=新映射();let o=JSON.parse(JSON);让遍历=(父级,字段)=>{让obj=父级;let path=“#REF:$”;if(字段!==未定义){obj=父[字段];path=objToPath.get(父)+(Array.isArray(父)`[${field}]`:`${field?'。'+字段:''}`);}objToPath.set(obj,路径);pathToObj.set(路径,对象);let ref=路径目标获取(obj);如果(ref)父[字段]=ref;for(让f在obj中)if(obj==对象(obj))遍历(obj,f);}横向(o);返回o;}// ---------------//测试1// ---------------让json=`{“L”:{“L”:{“v”:“lorem”,“叔叔”:{“L”:{“v”:“dolor”,“叔叔”:“#REF:$.L”},“R”:{“L”:{“v”:“坐”,“叔叔”:“#REF:$.L.L叔叔.L”},“R”:{“v”:“amet”,“叔叔”:“#REF:$.L.L叔叔.L”},“叔叔”:“#REF:$.L”}}},“R”:{“v”:“ipsum”,“叔叔”:“#REF:$.L.L叔叔”}},“R”:“#REF:$.L.L叔叔”}`;let testObject=parseRefJSON(json);console.log(“测试对象\n”,testObject);// ---------------//测试2// ---------------console.log('来自mathheadinclouds的测试答案:');let recovered=测试对象;let obj={//原始对象我:{五十: {v:“lorem”},R: {v:“ipsum”}},R:{五十: {v:“dolor”},R:{五十: {v:“坐”},R: {v:“amet”}}}}obj.R.L.uncle=对象L;obj.R..uncle=对象L;obj.R.L..uncle=obj.R.L;obj.R.R..uncle=obj.R.L;obj.L.L.uncle=对象R;obj.L.R.unncle=对象R;[目标L.L.v===恢复L.L.v,目标L.R.v===恢复L.R.v,目标R.L.v===恢复的R.L.v,目标R.R.L.v===恢复的R.R.L.v,obj.R.R.R.v===恢复的R.R.R.v,obj.R.L.包含==obj.L,对象.R.R.uncle==对象L,obj.R.L.包含==obj.R.L,obj.R.R.包含==obj.R.L,对象.L.L.uncle==对象R,obj.L.R.包含==obj.R,recovered.R.L叔叔==已恢复.L,恢复.R.R.叔叔==恢复.L,恢复.R.R.L叔叔==恢复.R.L,恢复.R.R.R.叔叔==恢复.R.L,recovered.L.L叔叔==恢复。R,已恢复.L.R叔叔==已恢复.R].forEach(x=>console.log('测试通过:'+x));

要将生成的JSON内容加载/保存到存储中,请使用以下代码:

localStorage.myObject = JSON.stringify(testObject, refReplacer());  // Save
testObject = parseRefJSON(localStorage.myObject);                   // Load

下面是danott发布的代码的一些扩展版本:

它还将实现本地存储中的删除值,并显示如何添加Getter和Setter层,

localstorage.setItem(预览,true)

你可以写

config.preview=真

好了,我们来了:

var PT=Storage.prototype

if (typeof PT._setItem >='u')
  PT._setItem = PT.setItem;
PT.setItem = function(key, value)
{
  if (typeof value >='u') //..undefined
    this.removeItem(key)
  else
    this._setItem(key, JSON.stringify(value));
}

if (typeof PT._getItem >='u')
  PT._getItem = PT.getItem;
PT.getItem = function(key)
{
  var ItemData = this._getItem(key)
  try
  {
    return JSON.parse(ItemData);
  }
  catch(e)
  {
    return ItemData;
  }
}

// Aliases for localStorage.set/getItem
get = localStorage.getItem.bind(localStorage)
set = localStorage.setItem.bind(localStorage)

// Create ConfigWrapperObject
var config = {}

// Helper to create getter & setter
function configCreate(PropToAdd){
    Object.defineProperty( config, PropToAdd, {
      get: function ()    { return (get(PropToAdd)    )},
      set: function (val) {         set(PropToAdd, val)}
    })
}
//------------------------------

// Usage Part
// Create properties
configCreate('preview')
configCreate('notification')
//...

// Configuration Data transfer
// Set
config.preview = true

// Get
config.preview

// Delete
config.preview = undefined

嗯,你可以用.bind(…)去掉别名部分。不过,我只是把它放进去,因为知道这一点真的很好。我花了几个小时才弄明白为什么一个简单的get=localStorage.getItem;不工作。

我找到了一种方法,使它可以处理具有循环引用的对象。

让我们制作一个具有循环引用的对象。

obj = {
    L: {
        L: { v: 'lorem' },
        R: { v: 'ipsum' }
    },
    R: {
        L: { v: 'dolor' },
        R: {
            L: { v: 'sit' },
            R: { v: 'amet' }
        }
    }
}
obj.R.L.uncle = obj.L;
obj.R.R.uncle = obj.L;
obj.R.R.L.uncle = obj.R.L;
obj.R.R.R.uncle = obj.R.L;
obj.L.L.uncle = obj.R;
obj.L.R.uncle = obj.R;

由于循环引用,我们不能在这里执行JSON.stringify。

LOCALSTORAGE.CYCLICJSON与普通JSON一样具有.stringify和.parse,但可以处理具有循环引用的对象。(“Works”表示解析(stringify(obj))和obj深度相等,并且具有相同的“内部等式”集合)

但我们可以使用快捷方式:

LOCALSTORAGE.setObject('latinUncles', obj)
recovered = LOCALSTORAGE.getObject('latinUncles')

然后,recovered将与obj“相同”,在以下意义上:

[
obj.L.L.v === recovered.L.L.v,
obj.L.R.v === recovered.L.R.v,
obj.R.L.v === recovered.R.L.v,
obj.R.R.L.v === recovered.R.R.L.v,
obj.R.R.R.v === recovered.R.R.R.v,
obj.R.L.uncle === obj.L,
obj.R.R.uncle === obj.L,
obj.R.R.L.uncle === obj.R.L,
obj.R.R.R.uncle === obj.R.L,
obj.L.L.uncle === obj.R,
obj.L.R.uncle === obj.R,
recovered.R.L.uncle === recovered.L,
recovered.R.R.uncle === recovered.L,
recovered.R.R.L.uncle === recovered.R.L,
recovered.R.R.R.uncle === recovered.R.L,
recovered.L.L.uncle === recovered.R,
recovered.L.R.uncle === recovered.R
]

以下是LOCALSTORAGE的实现

LOCALSTORAGE=(函数){“使用严格”;var ignore=[Boolean,Date,Number,RegExp,String];函数原语(项){if(项目类型==“对象”){if(item==null){return true;}对于(var i=0;i<ignore.length;i++){if(iteminstanceofignore[i]){return true;}}return false;}其他{返回true;}}功能婴儿(价值){return Array.isArray(value)?[] : {};}函数decycleIntoForest(对象,替换符){if(typeof replacer!==“函数”){replacer=函数(x){return x;}}object=替换器(对象);if(原语(对象))返回对象;var objects=[对象];var森林=[婴儿(对象)];var bucket=new WeakMap();//桶=对象的倒数bucket.set(对象,0);函数addToBucket(obj){var result=objects.length;objects.push(obj);bucket.set(对象,结果);返回结果;}函数isInBucket(obj){return bucket.has(obj);}函数processNode(源,目标){Object.keys(源).forEach(函数(键){var value=replacer(源[key]);if(基元(值)){target[key]={value:value};}其他{var ptr;if(isInBucket(值)){ptr=bucket.get(值);}其他{ptr=addToBucket(值);var newTree=婴儿(值);forest.push(newTree);processNode(value,newTree);}target[key]={pointer:ptr};}});}processNode(对象,林[0]);回归森林;};函数deForestInoCycle(林){var对象=[];var objectRequested=[];var todo=[];函数processTree(idx){if(对象中的idx)返回对象[idx];if(objectRequested[idx])返回null;objectRequested[idx]=true;var树=森林[idx];var node=Array.isArray(树)?[] : {};for(树中的var键){var o=树[key];如果(o中的“指针”){var ptr=o.pointer;var value=processTree(ptr);if(值==空){todo推送({node:节点,key:键,idx:ptr});}其他{node[key]=值;}}其他{if(o中的“值”){节点[key]=o.value;}其他{抛出新错误(“意外”)}}}objects[idx]=节点;返回节点;}var result=processTree(0);对于(var i=0;i<todo.length;i++){var项=todo[i];item.node[item.key]=对象[item.idx];}返回结果;};var控制台={日志:函数(x){var the=document.getElementById(''');.textContent=.textContent+'\n'+x;},分隔符:函数(){var the=document.getElementById(''');.textContent=.textContent+'\n***************************************';}}函数logCyclicObjectToConsole(根){var cycleFree=decycleIntoForest(根);var showed=cycleFree.map(函数(树,idx){return false;});var缩进增量=4;函数showItem(nodeSlot、indent、label){var leadingSpaces=''.repeat(缩进);var leadingSpacesPlus=“”.repeat(缩进+缩进增量);if(显示[nodeSlot]){console.log(leadingSpaces+label+'…请参见上文(object#'+nodeSlot+')');}其他{console.log(leadingSpaces+label+'object#'+nodeSlot);var tree=cycleFree[nodeSlot];show[nodeSlot]=true;Object.keys(树).forEach(函数(键){var entry=tree[key];if(条目中的“值”){console.log(leadingSpacesPlus+key+“:”+entry.value);}其他{if(条目中的“指针”){showItem(entry.pointer,indent+indentIncrement,key);}}});}}console.demiter();showItem(0,0,'root');};函数字符串(obj){return JSON.stringify(decycleIntoForest(obj));}函数解析(str){return deForestInoCycle(JSON.parse(str));}var CYLICJSON={decycleIntoForest:decycleIntoForest,deForestInoCycle:deForestIntoCycle,logCyclicObjectToConsole:logCyclicObject到控制台,丝状:丝状,解析:解析}函数setObject(名称,对象){var str=字符串(对象);localStorage.setItem(名称,str);}函数getObject(名称){var str=localStorage.getItem(名称);如果(str==null)返回null;返回解析(str);}返回{CYCLICJSON:CYCLICJSON,setObject:setObject,getObject:getObject}})();目标={我:{五十: {v:“lorem”},R: {v:“ipsum”}},R:{五十: {v:“dolor”},R:{五十: {v:“坐”},R: {v:“amet”}}}}obj.R.L.uncle=对象L;obj.R..uncle=对象L;obj.R.L..uncle=obj.R.L;obj.R.R..uncle=obj.R.L;obj.L.L.uncle=对象R;obj.L.R.unncle=对象R;//LOCALSTORAGE.setObject(“latinUncles”,对象)//recovered=LOCALSTORAGE.getObject('latinUncles')//fiddle内部不提供localStorage):本地存储.CYCLICJSON.logCyclicObjectToConsole(obj)putIntoLS=本地存储.CYCLICJSON.stringify(obj);recovered=本地存储.CYCLICJSON.parse(putIntoLS);LOCALSTORAGE.CYCLICJSON.logCyclicObjectToConsole(已恢复);var the=document.getElementById(''');.textContent=.textContent+'\n\n'+JSON.stringify([目标L.L.v===恢复L.L.v,目标L.R.v===恢复L.R.v,目标R.L.v===恢复的R.L.v,目标R.R.L.v===恢复的R.R.L.v,obj.R.R.R.v===恢复的R.R.R.v,obj.R.L.包含==obj.L,

我做了另一个只有20行代码的极简包装器,这样就可以使用它了:

localStorage.set('myKey',{a:[1,2,5], b: 'ok'});
localStorage.has('myKey');   // --> true
localStorage.get('myKey');   // --> {a:[1,2,5], b: 'ok'}
localStorage.keys();         // --> ['myKey']
localStorage.remove('myKey');

https://github.com/zevero/simpleWebstorage