Skip to content

Instantly share code, notes, and snippets.

@joepuzzo
Last active November 5, 2020 16:01
Show Gist options
  • Save joepuzzo/3697b61d2e4646d782e341031bdd6092 to your computer and use it in GitHub Desktop.
Save joepuzzo/3697b61d2e4646d782e341031bdd6092 to your computer and use it in GitHub Desktop.
Parses out functions from pure JSON
let replacer = (key, value) => {
// if we get a function, give us the code for that function
if (typeof value === 'function') {
return value.toString();
}
return value;
}
let reviver = (key, value) => {
if (typeof value === 'string'
&& value.indexOf('function') === 0) {
let functionTemplate = `(${value}).call(this)`;
return new Function(functionTemplate);
}
return value;
};
reviver = (key, value) => {
if (typeof value === 'string'
&& value.indexOf('function') === 0) {
let functionTemplate = `(${value})`;
return eval(functionTemplate);
}
return value;
}
const test = {
foo: 'bar',
baz: {
raz: 45
},
func: function(a,b) {
return a + b;
}
}
console.log('OBJ', test);
const str = JSON.stringify(test, replacer);
console.log('STR', str);
const parsed = JSON.parse(str, reviver);
console.log('OBJ', parsed);
console.log('RES', parsed.func(1,2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment