1

I wanted to store the object in local storage and I serialized the object using JSON.stringify. Then some of the inner attributes are missing after parse using JSON.parse.

I attached 2 images below to see the changes and appreciate it if anyone can answer a better solution for this. Thanks.

This object is just before stringified using JSON.

enter image description here

This object is stringified and parse using JSON

enter image description here

This is how i store and retreive data

enter image description here

enter image description here

Asbar Ali
  • 955
  • 1
  • 13
  • 26
  • Did you just use `JSON.stringify` and `JSON.parse`? Can you show us how you stringify and parse please – Sinan Yaman Dec 28 '20 at 11:22
  • 2
    functions are not valid values in JSON. When you stringify, `difficulty` and other function keys are ignored – adiga Dec 28 '20 at 11:24
  • ohh then what is the solution to store the whole JSON object in local storage? – Asbar Ali Dec 28 '20 at 11:25
  • Does this answer your question? [How to store a javascript function in JSON](https://stackoverflow.com/questions/36517173/how-to-store-a-javascript-function-in-json) – pilchard Dec 28 '20 at 12:07

1 Answers1

2

Json.Stringify does not pass functions into the stringified JSON, i.e. functions will not be copied into the string as functions are not valid JSON objects. In your case, the difficulty is a function and as such won't be copied.

You can include the function by using a replacer:

JSON.stringify({
   /* your object here */
}, function(key, val) {
        return (typeof val === 'function') ? '' + val : val;
});
chingucoding
  • 894
  • 7
  • 17
  • Do u know how to parse the stringified functions? – Asbar Ali Dec 29 '20 at 11:51
  • You can use the javascript `eval` function and a custom reviver. You can read more about this here: https://stackoverflow.com/questions/36517173/how-to-store-a-javascript-function-in-json – chingucoding Dec 29 '20 at 18:46