Created
April 29, 2010 21:57
-
-
Save quickredfox/384323 to your computer and use it in GitHub Desktop.
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
/* | |
"unsafe" JSON converters, allows one to also include functions | |
(does nto support native functions but an example workaround is given) | |
*/ | |
JSON.unsafeStringify = function(obj){ | |
if(typeof obj == 'object'){ | |
if(obj instanceof Array) for(var i=0;i<obj.length;i++) obj[i] = JSON.unsafeStringify(obj[i]); | |
else for(var k in obj) obj[k] = JSON.unsafeStringify(obj[k]); | |
}; | |
if(typeof obj == 'function') obj = obj.toString(); | |
if((/native code/).test(obj)) obj = 'function(){}'; | |
return JSON.stringify(obj); | |
}; | |
JSON.unsafeParse = function(str){ | |
var obj = JSON.parse(str); | |
return JSON.unsafeParse.evalFunctions(obj); | |
}; | |
// helper | |
JSON.unsafeParse.evalFunctions = function(obj){ | |
if(typeof obj == 'object'){ | |
if(obj instanceof Array) for(var i=0;i<obj.length;i++) obj[i] = JSON.unsafeParse(obj[i]); | |
else for(var k in obj) obj[k] = JSON.unsafeParse(obj[k]); | |
}; | |
if(typeof obj =='string' && (/^function/).test(obj)) return (new Function('return '+obj+';'))(); | |
return obj; | |
}; | |
/* example */ | |
// var json = {foo:'bar',fn:function(){ return "qwer"},a:Math.log}; // will not work with natives | |
var json = {foo:'bar',fn:function(){ return "qwer"},a:function(){return Math.log.apply(null,arguments)}}; // but this will | |
console.debug(JSON.unsafeParse(JSON.unsafeStringify(json))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment