Skip to content

Instantly share code, notes, and snippets.

@livingston
Created March 9, 2011 12:37
Show Gist options
  • Save livingston/862112 to your computer and use it in GitHub Desktop.
Save livingston/862112 to your computer and use it in GitHub Desktop.
/* Parses JSON with function body as a string into JavaScript object */
var parseJSONwithFunctions = function (JSONdata) {
var root = document.documentElement,
sandbox = document.createElement('script'),
code = "var fn = {", i;
for (i in JSONdata) {
if( JSONdata.hasOwnProperty(i) ) {
code += i + " : " + JSONdata[i] + ",";
}
}
code = code.replace(/,$/, '') + " };";
try {
sandbox.appendChild(document.createTextNode(code));
} catch (e) {
sandbox.text = code;
}
root.insertBefore(sandbox, root.firstChild);
root.removeChild(sandbox);
root = sandbox = null;
return fn;
};
var sampleJSON = { id: "10", getID: "function () { alert(this.id) }" };
@livingston
Copy link
Author

BUG: this fails for String data in the JSON

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment