Last active
November 5, 2020 16:01
-
-
Save joepuzzo/3697b61d2e4646d782e341031bdd6092 to your computer and use it in GitHub Desktop.
Parses out functions from pure JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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