[英]How to store a JavaScript object with methods in local storage?
I have a neural network library that I'm creating that contains nested objects stored in arrays. 我正在创建一个神经网络库,其中包含存储在数组中的嵌套对象。 I need to be able to save the states of these objects to local storage.
我需要能够将这些对象的状态保存到本地存储中。 I've attempted to use JSON.stringify to convert the highest level network object into something I can save, but when I
JSON.parse()
it back, it doesn't contain the methods. 我试图使用JSON.stringify将最高级别的网络对象转换为我可以保存的东西,但是当我将
JSON.parse()
返回时,它不包含方法。
The code can be found here. 可以在这里找到代码。
Thanks in advance for your help. 在此先感谢您的帮助。
Most of them won't recommend persisting function(behavior) inside JSON object, that is intended to carry only data. 他们中的大多数人不建议在JSON对象中保留仅用于携带数据的功能(行为)。 In case if you want to serialize the object with function, you need to override them, the below code would help you that.
如果要使用功能序列化对象,则需要重写它们,以下代码将为您提供帮助。
This will help you to serialize function. 这将帮助您序列化功能。
var json = function(obj){ return JSON.stringify(obj, function(key, value) {
if (typeof value === 'function') {
return value.toString();
} else {
return value;
}
})};
I've created an object rama for testing, the output of json(rama) would be 我创建了一个对象rama进行测试, json(rama)的输出为
"{\"myName\":\"Ramasamy Kasiviswanathan\",\"myfunction\":\"function(input){\\nconsole.log('input', input);\\n}\"}"
Storing in localStorage, 存储在localStorage中,
localStorage.setItem('ramaLocal',json(rama));
Retrieving value from LocalStorage, 从LocalStorage检索值,
ramadeserialize = eval("JSON.parse(localStorage.getItem('ramaLocal'))");
O/P would be: O / P为:
Object { myName: "Ramasamy Kasiviswanathan", myfunction: "function(input){\nconsole.log('input', input);\n}" }
Reference: json.stringify does not process object methods 参考: json.stringify不处理对象方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.