0

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.

Shadow
  • 7,997
  • 4
  • 45
  • 55
  • 2
    You cannot store functions in local storage. You will want to [revive your objects](https://stackoverflow.com/q/11810028/1048572). – Bergi Dec 12 '17 at 03:03
  • To add to @Bergi's answer, you shouldn't need to store functions in localStorage either. If your functions are written in such a way that they have data baked in, it should be possible to rewrite whatever generates these functions in such a way that the data is what is stored, and the function is independent. – Jake Dec 12 '17 at 03:04

1 Answers1

-1

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