Created
November 17, 2013 21:46
-
-
Save Hoff97/7518680 to your computer and use it in GitHub Desktop.
JSON but with function de- and encoding.
Just use jsonWF to make a JSON string and objWF to make a Object from a JSON string.
All methods will remain.
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
function jsonWF(obj) | |
{ | |
inject(obj,"funcConvert","self"); | |
var ret = JSON.stringify(obj,funcStringify); | |
cleanProb(obj,"funcConvert"); | |
return ret; | |
} | |
function objWF(str) | |
{ | |
return transformFuncs(JSON.parse(str)); | |
} | |
function transformFuncs(obj) | |
{ | |
for(key in obj) | |
{ | |
if(typeof obj[key] == "object") | |
{ | |
transformFuncs(obj[key]); | |
} | |
} | |
setFuncs(obj,obj["funcConvert"]); | |
cleanProb(obj,"funcConvert",1); | |
return obj; | |
} | |
function setFuncs(obj,funcs) | |
{ | |
for(key in funcs) | |
{ | |
assignFuncFromStr(obj,key,funcs[key]); | |
} | |
} | |
function assignFuncFromStr(obj,name,str) | |
{ | |
eval("obj." + name + " = " + str + ";"); | |
} | |
function funcStringify(key,value) | |
{ | |
if(key=="funcConvert") | |
{ | |
var self = value.self(); | |
return functionsToObj(self); | |
} | |
return value; | |
} | |
function functionsToObj(obj) | |
{ | |
var ret = {}; | |
for(key in obj) | |
{ | |
if(typeof obj[key] == "function") | |
{ | |
ret[key] = obj[key].toString(); | |
} | |
} | |
return ret; | |
} | |
function cleanProb(obj,name,maxdepth=null,depth=0) | |
{ | |
if(depth<maxdepth || maxdepth==null) | |
{ | |
depth++; | |
if(typeof obj == "object") | |
{ | |
for(var key in obj) | |
{ | |
cleanProb(obj[key],name,maxdepth,depth); | |
} | |
delete obj[name]; | |
} | |
} | |
} | |
function inject(obj,name,injection,maxdepth=null,depth=0) | |
{ | |
if(depth<maxdepth || maxdepth==null) | |
{ | |
depth++; | |
if(typeof obj == "object") | |
{ | |
for(var key in obj) | |
{ | |
inject(obj[key],name,injection,maxdepth,depth); | |
} | |
obj[name] = injection; | |
if(injection==="self") | |
{ | |
obj[name] = {self:function(){return obj;}}; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment