简体   繁体   中英

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.

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. 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

 "{\"myName\":\"Ramasamy Kasiviswanathan\",\"myfunction\":\"function(input){\\nconsole.log('input', input);\\n}\"}"

Storing in localStorage,

localStorage.setItem('ramaLocal',json(rama));

Retrieving value from LocalStorage,

 ramadeserialize = eval("JSON.parse(localStorage.getItem('ramaLocal'))");

O/P would be:

Object { myName: "Ramasamy Kasiviswanathan", myfunction: "function(input){\nconsole.log('input', input);\n}" }

Reference: json.stringify does not process object methods

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM