Search code examples
javascriptjsonobjectparsingstringify

How can I JSON stringify and then parse an object with functions? (JavaScript)


I have an object with both attributes and functions, and I want to be able to stringify them into JSON, then parse them back out again for a save-load system. Keep in mind, the data has circular components.

I tried using flatted, but then I ran into the problem where I did not know how to revive the object properly. I'm still new to JSON, so any help is appreciated.


Solution

  • From MDN:

    undefined, Function, and Symbol values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to null (when found in an array).

    So what you want is just not possible.

    Even if you would construct a string yourself that resembles a 'stringified function', then JSON.parse() will not be able to handle it like you would want it to do.