Search code examples
javascriptjsonprototypefunction-objectto-json

Is it possible to override Function.prototype.toJSON so that JSON.stringify could work with functions?


Or maybe even override some portion of JSON.parse to parse functions? This isn't time sensitive, I built work arounds in my code, but with the eval function, you would think that turning functions into strings and back would be a piece of cake.


Solution

  • It's possible, but weird, and you of course wouldn't have access to any of the outer scope of the parsed function. Call toString to get the function's source code, trim out the brackets so you just have the function body, and have Function.prototype.toJSON return that. Then when parsing, call new Function on the string:

    Function.prototype.toJSON = function() {
      // trim out beginning and end {}s
      return this.toString().match(/[^{]*(?=}$)/)[0];
    };
    
    const fn = () => {
      console.log('foo');
    };
    const json = JSON.stringify({
      str: 'str',
      fn
    });
    console.log(json);
    const parsed = JSON.parse(json);
    const parsedFn = new Function(parsed.fn);
    parsedFn();

    But there shouldn't be a need to do this in 99% of situations. Whatever the actual issue is, there's probably a more elegant solution.