Javascript stringify with functions 1

Javascript stringify with functions

function stringifyWithFunctions(object) {
  return JSON.stringify(object, (key, val) => {
    if (typeof val === 'function') {
      return `(${val})`; // make it a string, surround it by parenthesis to ensure we can revive it as an anonymous function
    }
    return val;
  });
};

function parseWithFunctions(obj) {
  return JSON.parse(obj, (k, v) => {
    if (typeof v === 'string' && v.indexOf('function') >= 0) {
      return eval(v);
    }
    return v;
  });
};

Here is what the above code is Doing:
1. We’re creating a function called stringifyWithFunctions that takes an object as an argument.
2. We’re using JSON.stringify to stringify the object.
3. We’re using a replacer function to replace any functions with a stringified version of the function.
4. We’re creating a function called parseWithFunctions that takes an object as an argument.
5. We’re using JSON.parse to parse the object.
6. We’re using a reviver function to revive any functions that were stringified.
7. We’re using eval to evaluate the stringified function.

Similar Posts